配置Spring Boot通過@ConditionalOnProperty來控制Configuration是否生效
1、matchIfMissing屬性:從application.properties中讀取某個屬性值,如果該值為空,默認值為true
@Configuration
@ConditionalOnClass({ Feign.class }) @ConditionalOnProperty(value = "feign.oauth2.enabled", matchIfMissing = true) public class OAuth2FeignAutoConfiguration { @Bean @ConditionalOnBean(OAuth2ClientContext.class) public RequestInterceptor oauth2FeignRequestInterceptor(OAuth2ClientContext oauth2ClientContext) { return new OAuth2FeignRequestInterceptor(oauth2ClientContext); } }
2、havingValue屬性:通過其兩個屬性name以及havingValue來實現的,其中name用來從application.properties中讀取某個屬性值,如果該值為空,則返回false;如果值不為空,則將該值與havingValue指定的值進行比較,如果一樣則返回true;否則返回false。如果返回值為false,則該configuration不生效;為true則生效。
@Configuration //如果synchronize在配置文件中並且值為true @ConditionalOnProperty(name = "synchronize", havingValue = "true") public class SecondDatasourceConfig { @Bean(name = "SecondDataSource") @Qualifier("SecondDataSource") @ConfigurationProperties(prefix = "spring.second.datasource") public DataSource jwcDataSource() { return DataSourceBuilder.create().build(); } }
