Spring Boot 开发过程中我们经常会写一些 Configuration Class 来定义 Beans。只要你的代码没问题,这些 Configuration Class 默认都会生效,类下的 Beans 都会被加载。但在实际情况中,我们在不同的环境,或者不同一些场景下我们可能需要禁用这些 Configuration Class。而这篇文章就给大家总结了一些灵活控制 Configuration Class 是否生效的方法。
这些方法并不局限于 @Configuration,参考:how-to-conditionally-enable-or-disable-scheduled-jobs-in-spring
方法一:通过 @Profile 注解
@Profile 注解可以让你声明一个 Configuration Class 仅在相应 Profiles Active 时才会生效。
package xxx;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
@Profile({"dev","test"})
public class XXXConfiguration {
@Bean
public XXX A() {
return XXX;
}
@Bean
public XXX B() {
return XXX;
}
}
上面这段代码就是说,仅当 profile “dev” 或者 “test” 是 active 时(即 spring.profiles.active=dev or spring.profiles.active=test or spring.profiles.active=dev,test 时),XXXConfiguration Class 才会被加载。
方法二:通过 @ConditionalOnProperty 注解
通过 Profiles 来界定一个 Configuration Class 是否应该被加载是我们最常碰到的需求,换句话说 @Profile 可以解决大部分问题。但有时候,我们也希望通过一个专门的配置(在 application.properties/application.yaml 里面配置一下)这种方式来控制是否加载一个对应的 Configuration Class。这时,我们可以用到 @ConditionalOnProperty。
package xxx;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
@ConditionalOnProperty(name="xxx.enabled", havingValue = "true")
public class XXXConfiguration {
@Bean
public XXX A() {
return XXX;
}
@Bean
public XXX B() {
return XXX;
}
}
此时,仅当配置项“xxx.enabled”的值为“true时,XXXConfiguration Class 才会被加载。如果“xxx.enabled”为空则 XXXConfiguration Class 也不会被加载。
网友评论