0

0

动态加载 Spring Beans 的最佳实践

DDD

DDD

发布时间:2025-08-16 20:42:02

|

380人浏览过

|

来源于php中文网

原创

动态加载 spring beans 的最佳实践

本文介绍了如何在 Spring 应用程序中基于环境动态加载不同的 Bean 实现。通过使用 @Conditional 注解和手动配置 Bean,可以根据特定条件选择性地加载 DoThingService 或 NoopService,从而避免了 Bean 冲突问题,并简化了单元测试。

在 Spring 应用程序开发中,经常会遇到需要根据不同的环境(例如:生产环境、测试环境、开发环境)加载不同的 Bean 实现的情况。 一种常见的做法是使用 @Conditional 注解,但是当多个 Bean 实现了同一个接口时,可能会出现 Spring 无法区分应该注入哪个 Bean 的问题,导致 No qualifying bean of type ... available 错误。

本文将介绍一种通过手动配置 Bean 和使用 @Conditional 注解来解决这个问题的方法。

问题描述

假设我们有一个 DoThingInterface 接口,以及两个实现类 DoThingService 和 NoopService。 DoThingService 实现了具体的业务逻辑,而 NoopService 则是一个空操作,用于在某些环境下禁用该功能。

public interface DoThingInterface {
    void doThing();
}

public class DoThingService implements DoThingInterface {
    @Override
    public void doThing() {
        // business logic
    }
}

public class NoopService implements DoThingInterface {
    @Override
    public void doThing() {
        // noop
    }
}

我们希望根据特定的条件(例如:环境、配置属性)选择性地加载 DoThingService 或 NoopService。 传统的做法是使用 @Conditional 注解在 DoThingService 和 NoopService 类上,然后通过 @Autowired 注入 DoThingInterface。

@Conditional(DoThingCondition.class)
@Component
public class DoThingService implements DoThingInterface {
    @Override
    public void doThing() {
       // business logic
    }
}

@Conditional(DoNotDoThingCondition.class)
@Component
public class NoopService implements DoThingInterface {
    @Override
    public void doThing() {
        // noop
    }
}

public class AppController {

    @Autowired
    private DoThingInterface doThingService;

    public void businessLogicMethod() {
        doThingService.doThing();
    }
}

但是,这种做法会导致 Spring 无法区分应该注入哪个 Bean,因为 DoThingService 和 NoopService 都实现了 DoThingInterface 接口。

解决方案

解决这个问题的方法是将 @Conditional 注解移动到配置类中,并手动创建 Bean。

1. 创建 Condition 类

首先,我们需要创建两个 Condition 类,用于判断是否应该加载 DoThingService 或 NoopService。

易通cmseasy免费的企业建站程序3.0 UTF-8 日文版
易通cmseasy免费的企业建站程序3.0 UTF-8 日文版

九州易通科技开发的核心产品易通企业网站系统(CmsEasy3.0)是充分按照SEO最佳标准来开发,营销实用性非常强企业建站系统。灵活的静态化控制,可以自定义字段,自定义模板,自定义表单,自定义URL,交叉绑定分类,地区,专题等多元化定制大大增加了企业网站的各种需求空间。强大的模板自定义可以轻松打造出个性的栏目封面,文章列表,图片列表,下载列表,分类列表,地区列表等等。主体功能列表如下:支持生成ht

下载
public class DoNotDoTheThingCondition implements Condition {
    @Override
    public boolean matches(ConditionalContext context) {
        // 根据环境、配置属性等条件判断是否应该加载 NoopService
        return !(/* condition logic */);
    }
}

public class DoThingCondition implements Condition {
    @Override
    public boolean matches(ConditionalContext context) {
        // 根据环境、配置属性等条件判断是否应该加载 DoThingService
        return /* condition logic */;
    }
}

示例 Condition 实现:

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

public class DoNotDoTheThingCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String region = System.getenv("REGION"); // 假设从环境变量中获取区域信息
        String profile = context.getEnvironment().getProperty("spring.profiles.active"); // 获取激活的 Profile

        // 简化后的条件判断:如果不是生产环境,则不执行 DoThing
        return !(region != null && region.equals("someRegion") && profile != null && profile.contains("prod"));
    }
}

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

public class DoThingCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String region = System.getenv("REGION"); // 假设从环境变量中获取区域信息
        String profile = context.getEnvironment().getProperty("spring.profiles.active"); // 获取激活的 Profile

        // 简化后的条件判断:如果是生产环境,则执行 DoThing
        return region != null && region.equals("someRegion") && profile != null && profile.contains("prod");
    }
}

2. 创建配置类

然后,创建一个配置类,并使用 @Conditional 注解在 Bean 方法上。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DoThingConfiguration {
    @Conditional(DoThingCondition.class)
    @Bean
    public DoThingInterface doThingService() {
        return new DoThingService();
    }

    @Conditional(DoNotDoTheThingCondition.class)
    @Bean
    public DoThingInterface noopService() {
        return new NoopService();
    }
}

3. 修改 Controller 类

最后,修改 Controller 类,通过 @Autowired 注入 DoThingInterface。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AppController {

    @Autowired
    private DoThingInterface doThingService;

    public void businessLogicMethod() {
        doThingService.doThing();
    }
}

总结

通过将 @Conditional 注解移动到配置类中,并手动创建 Bean,可以避免 Spring 无法区分应该注入哪个 Bean 的问题。 这种做法的优点是可以更加灵活地控制 Bean 的加载,并且可以简化单元测试,因为不需要 Mock NoopService。

注意事项:

  • 需要保证 DoThingCondition 和 DoNotDoTheThingCondition 之间的互斥性,即只有一个 Condition 能够匹配。
  • 在实际开发中,Condition 的实现应该根据具体的业务需求进行调整。
  • 这种方法需要在配置类中手动创建 Bean,可能会增加代码的复杂性。

总而言之,这种方法提供了一种在 Spring 应用程序中动态加载 Bean 的有效方式,特别是在需要根据环境或配置选择不同实现的情况下。

相关专题

更多
spring框架介绍
spring框架介绍

本专题整合了spring框架相关内容,想了解更多详细内容,请阅读专题下面的文章。

96

2025.08.06

硬盘接口类型介绍
硬盘接口类型介绍

硬盘接口类型有IDE、SATA、SCSI、Fibre Channel、USB、eSATA、mSATA、PCIe等等。详细介绍:1、IDE接口是一种并行接口,主要用于连接硬盘和光驱等设备,它主要有两种类型:ATA和ATAPI,IDE接口已经逐渐被SATA接口;2、SATA接口是一种串行接口,相较于IDE接口,它具有更高的传输速度、更低的功耗和更小的体积;3、SCSI接口等等。

980

2023.10.19

PHP接口编写教程
PHP接口编写教程

本专题整合了PHP接口编写教程,阅读专题下面的文章了解更多详细内容。

39

2025.10.17

硬盘接口类型介绍
硬盘接口类型介绍

硬盘接口类型有IDE、SATA、SCSI、Fibre Channel、USB、eSATA、mSATA、PCIe等等。详细介绍:1、IDE接口是一种并行接口,主要用于连接硬盘和光驱等设备,它主要有两种类型:ATA和ATAPI,IDE接口已经逐渐被SATA接口;2、SATA接口是一种串行接口,相较于IDE接口,它具有更高的传输速度、更低的功耗和更小的体积;3、SCSI接口等等。

980

2023.10.19

PHP接口编写教程
PHP接口编写教程

本专题整合了PHP接口编写教程,阅读专题下面的文章了解更多详细内容。

39

2025.10.17

苹果官网入口直接访问
苹果官网入口直接访问

苹果官网直接访问入口是https://www.apple.com/cn/,该页面具备0.8秒首屏渲染、HTTP/3与Brotli加速、WebP+AVIF双格式图片、免登录浏览全参数等特性。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

115

2025.12.24

拼豆图纸在线生成器
拼豆图纸在线生成器

拼豆图纸生成器有PixelBeads在线版、BeadGen和“豆图快转”;推荐通过pixelbeads.online或搜索“beadgen free online”直达官网,避开需注册的诱导页面。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

84

2025.12.24

俄罗斯搜索引擎yandex官方入口地址(最新版)
俄罗斯搜索引擎yandex官方入口地址(最新版)

Yandex官方入口网址是https://yandex.com。用户可通过网页端直连或移动端浏览器直接访问,无需登录即可使用搜索、图片、新闻、地图等全部基础功能,并支持多语种检索与静态资源精准筛选。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

553

2025.12.24

JavaScript ES6新特性
JavaScript ES6新特性

ES6是JavaScript的根本性升级,引入let/const实现块级作用域、箭头函数解决this绑定问题、解构赋值与模板字符串简化数据处理、对象简写与模块化提升代码可读性与组织性。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

155

2025.12.24

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
10分钟--Midjourney创作自己的漫画
10分钟--Midjourney创作自己的漫画

共1课时 | 0.1万人学习

Midjourney 关键词系列整合
Midjourney 关键词系列整合

共13课时 | 0.8万人学习

AI绘画教程
AI绘画教程

共2课时 | 0.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号