SpringBoot4.0新特性-BeanRegistrar

Spring 7.0引入了一种新的更方便更灵活的注册Bean的方式-BeanRegistrar。它是以编程方式根据条件动态做Bean的注入,并且可以一次注入多个Bean。

举个例子:

现在有一个EnvService,有2个实现类ProductionServiceNonProductionService

java 复制代码
public interface EnvService{
   String getEnv();
}
public class ProductionService implements EnvService{
    @Override
    public String getEnv() {
        return "Production";
    }
}
public class NonProductionService implements EnvService {
    @Override
    public String getEnv() {
        return "NonProduction";
    }
}

现在想实现:如果是生产环境就启用ProductionService,否则就启用NonProductionService,用BeanRegistrar如何来实现呢?

使用起来主要有2步:

  • BeanRegistrar接口实现
java 复制代码
public class EnvBeanRegistrar implements BeanRegistrar {
    @Override
    public void register(BeanRegistry registry, Environment env) {
        if(env.matchesProfiles("prod")){
            registry.registerBean("envService", ProductionService.class);
        } else {
            registry.registerBean("envService", NonProductionService.class);
        }
    }
}
  • @Import导入实现类
java 复制代码
@Configuration(proxyBeanMethods = false)
@Import(EnvBeanRegistrar.class)
public class BeanRegistrarConfig {
}
  • 测试一下
java 复制代码
@RestController
@RequestMapping("api/bean-registrar")
public class BeanRegistrarController {
    @Autowired
    private EnvBeanRegistrar.EnvService envService;
    @GetMapping(path = "/demo")
    public String demo() throws Exception{
        return envService.getEnv();
    }
}

可以切换spring.profiles.active测试不同的输出情况。

更多SpringBoot4.0的新特性,请参考:SpringBoot4.0新特性

相关推荐
NE_STOP3 小时前
springMVC-HTTP消息转换器与文件上传、下载、异常处理
spring
华仔啊5 小时前
挖到了 1 个 Java 小特性:var,用完就回不去了
java·后端
SimonKing6 小时前
SpringBoot整合秘笈:让Mybatis用上Calcite,实现统一SQL查询
java·后端·程序员
日月云棠21 小时前
各版本JDK对比:JDK 25 特性详解
java
用户8307196840821 天前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
JavaGuide1 天前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code
IT探险家1 天前
Java 基本数据类型:8 种原始类型 + 数组 + 6 个新手必踩的坑
java
花花无缺1 天前
搞懂new 关键字(构造函数)和 .builder() 模式(建造者模式)创建对象
java
用户908324602731 天前
Spring Boot + MyBatis-Plus 多租户实战:从数据隔离到权限控制的完整方案
java·后端
桦说编程1 天前
实战分析 ConcurrentHashMap.computeIfAbsent 的锁冲突问题
java·后端·性能优化