发现了Spring boot中有个注解@ConditionalOnProperty,这个注解能够控制某个configuration是否生效。具体操作是通过其两个属性name以及havingValue来实现的,其中name用来从application.properties中读取某个属性值,如果该值为空,则返回false;如果值不为空,则将该值与havingValue指定的值进行比较,如果一样则返回true;否则返回false。如果返回值为false,则该configuration不生效;为true则生效。
代码:
@Configuration
@ConditionalOnWebApplication
@AutoConfigureBefore({TestConfiguration.class})
@ConditionalOnProperty(prefix = "framework.web.filter", name = "enabled", havingValue = "true")
public class WebMvcConfiguration {
@Bean
@ConditionalOnMissingBean
public TestFilter testFilter() {
return new TestFilter();
}
}
配置文件:(如果去掉改配置文件 则上面这个bean不会生效)
framework.web.filter.enabled=true
改注解还有个字段: matchIfMissing=true 默认为false 意思就是说就是没配置framework.web.filter.enabled属性也会生效