springboot 允许通过配置文件控制 Bean 的加载。
1.使用 @ConditionalOnProperty 注解
@ConditionalOnProperty 注解可以根据配置文件中的属性值来决定是否加载 Bean。
1.1.在配置文件中添加属性
app.feature.enabled=true
1.2.在 Bean 定义上添加 @ConditionalOnProperty 注解
@ConditionalOnProperty(name = "app.feature.enabled", havingValue = "true")
@Bean
public MyFeature myFeature() {
return new MyFeature();
}
当 app.feature.enabled 的值为 true 时,MyFeature Bean 将被加载;否则,不会被加载。