0

0

动态加载 Spring Beans 的正确姿势

心靈之曲

心靈之曲

发布时间:2025-08-16 20:26:24

|

413人浏览过

|

来源于php中文网

原创

动态加载 spring beans 的正确姿势

本文旨在解决在 Spring 应用中,根据运行环境动态加载不同 Bean 实现的问题。通过使用 @Conditional 注解和手动创建 Bean 的方式,可以优雅地实现基于环境的 Bean 动态加载,避免了 Spring 无法区分多个实现了同一接口的 Bean 的问题,并提供了清晰的配置和易于测试的方案。

在 Spring 应用开发中,经常会遇到需要根据不同的环境(例如:开发、测试、生产)加载不同的 Bean 实现的场景。例如,在生产环境中执行实际的业务逻辑,而在测试环境中则使用 Mock 对象或者 No-op 实现。本文将介绍一种使用 @Conditional 注解和手动创建 Bean 的方法,来实现动态加载 Spring Beans,解决 Spring 无法区分多个实现了同一接口的 Bean 的问题。

问题描述

假设我们有一个接口 DoThingInterface,以及两个实现了该接口的类:DoThingService 和 NoopService。DoThingService 负责执行实际的业务逻辑,而 NoopService 则是一个空操作的实现。我们希望根据当前环境来决定加载哪个 Bean。

一种常见的错误做法是直接在 DoThingService 和 NoopService 类上使用 @Conditional 注解,如下所示:

public interface DoThingInterface {
    void doThing();
}

@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
    }
}

@Component
public class AppController {

    @Autowired
    private DoThingInterface doThingService;

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

在这种情况下,即使 DoThingCondition 和 DoNotDoThingCondition 是互斥的,Spring 仍然会尝试同时创建 DoThingService 和 NoopService 的 Bean,并抛出 NoUniqueBeanDefinitionException 异常,因为 Spring 无法确定应该注入哪个 Bean 到 AppController 中。

解决方案:使用配置类和手动创建 Bean

正确的做法是将 @Conditional 注解移动到配置类中,并手动创建 Bean。具体步骤如下:

  1. 定义 Condition 类:

首先,定义两个 Condition 类,用于判断是否应该创建对应的 Bean。

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 = "someRegion";
        String profile = "prod";
        return !(region.equals(region) && 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 = "someRegion";
        String profile = "prod";
        return (region.equals(region) && profile.contains("prod"));
    }
}

注意: 上述代码中 region 和 profile 变量需要替换为实际的获取逻辑,例如从环境变量、配置文件或 Spring 的 Environment 中获取。

  1. 创建配置类:

创建一个配置类,并使用 @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();
    }
}
  1. 定义接口和实现类:

定义接口 DoThingInterface 和两个实现类 DoThingService 和 NoopService。

摄图AI
摄图AI

摄图网旗下AI视觉创作平台

下载
public interface DoThingInterface {
    void doThing();
}

import org.springframework.stereotype.Service;

@Service // 可选,如果需要在其他地方注入该Bean
public class DoThingService implements DoThingInterface {
    @Override
    public void doThing() {
        // business logic
        System.out.println("Doing the thing!");
    }
}

import org.springframework.stereotype.Service;

@Service // 可选,如果需要在其他地方注入该Bean
public class NoopService implements DoThingInterface {
    @Override
    public void doThing() {
        // Noop
        System.out.println("Noop!");
    }
}
  1. Controller 的修改:

Controller 的修改保持不变,Spring 会根据配置自动注入正确的 Bean。

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();
    }
}

完整示例代码

以下是完整的示例代码:

Condition 类:

// DoNotDoTheThingCondition.java
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 = "someRegion";
        String profile = "prod";
        return !(region.equals(region) && profile.contains("prod"));
    }
}

// DoThingCondition.java
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 = "someRegion";
        String profile = "prod";
        return (region.equals(region) && profile.contains("prod"));
    }
}

配置类:

// DoThingConfiguration.java
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();
    }
}

服务类:

// DoThingInterface.java
public interface DoThingInterface {
    void doThing();
}

// DoThingService.java
import org.springframework.stereotype.Service;

@Service
public class DoThingService implements DoThingInterface {
    @Override
    public void doThing() {
        System.out.println("Doing the thing!");
    }
}

// NoopService.java
import org.springframework.stereotype.Service;

@Service
public class NoopService implements DoThingInterface {
    @Override
    public void doThing() {
        System.out.println("Noop!");
    }
}

Controller 类:

// AppController.java
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 动态加载。这种方法具有以下优点:

  • 清晰的配置: 配置集中在配置类中,易于理解和维护。
  • 易于测试: 可以通过修改 Condition 类的逻辑来模拟不同的环境,方便进行单元测试。
  • 避免冲突: 确保只有一个 Bean 被加载,避免了 NoUniqueBeanDefinitionException 异常。

注意事项:

  • 需要确保 Condition 类的逻辑正确,并且条件是互斥的,以避免同时加载多个 Bean。
  • 在 Condition 类中获取环境信息时,需要注意线程安全问题。

希望本文能够帮助你更好地理解和使用 @Conditional 注解,实现动态加载 Spring Beans。

相关专题

更多
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

线程和进程的区别
线程和进程的区别

线程和进程的区别:线程是进程的一部分,用于实现并发和并行操作,而线程共享进程的资源,通信更方便快捷,切换开销较小。本专题为大家提供线程和进程区别相关的各种文章、以及下载和课程。

463

2023.08.10

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

苹果官网直接访问入口是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

热门下载

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

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
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号