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新特性

相关推荐
Bs_MoneyMagnet1 分钟前
基于springboot+vue的爱心众筹系统的设计与实现 源码+文档
java·vue.js·spring boot·后端·spring·管理系统
名字还没想好☜16 分钟前
Java Collectors.groupingBy 进阶:多级分组、下游收集器与统计聚合一次搞定
java·windows·后端·python·spring
Wang's Blog20 分钟前
Java框架快速入门: Spring Security+OAuth2之前端按钮级安全与路由守卫
java·安全·spring
ocean210337 分钟前
2025-2026年Java语言及生态面试高频知识点洞察
java·开发语言·面试
2302_11144 分钟前
java时间类型
java·开发语言
用户8181870627461 小时前
第25章 Redis集群脑裂实录:一次真实故障复盘
java·后端
运行时异常1 小时前
【WMS 仓储系统集成 AI Agent 实战】第 6 讲:RAG 知识库——“输出简单流程“为什么检索不到任何东西
java
小七在进步1 小时前
类和对象(三)
java·开发语言
夜不会漫长1 小时前
C++:类和对象(1)
java·开发语言·c++
czt_java1 小时前
Java文件IO核心知识点总结
java·开发语言