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

相关推荐
子非衣10 小时前
Java使用Aspose进行Word转PDF时异常卡主问题
java·pdf·word
此生决int10 小时前
Java面向对象进阶精讲:抽象类、接口、内部类与Object类万字详解
java
阿维的博客日记10 小时前
‘version‘ must be a constant version but is ‘${revision}‘
java·spring boot·后端
C+++Python10 小时前
C++ 常量全面讲解
java·开发语言·c++
程序员小羊!10 小时前
17 Maven
java·maven
C+-C资深大佬10 小时前
C++ 数字与字符串互转
java·c++·算法
陈猪的杰咪10 小时前
DeepSeek V4 中转方案全解析 | Flash 成本仅为 GPT 的 1/90
java·人工智能·gpt·spring
zlpzlpzyd10 小时前
spring boot 4.1发布
java·数据库·spring boot
无籽西瓜a10 小时前
Plan-and-Execute 里的 DAG 是怎么工作的
java·后端·ai·agent·dag