在创建bean时,我需要检查YAML属性文件是否满足两个条件。我怎么做,因为@ConditionalOnProperty
注释只支持一个属性?
使用@ConditionalOnExpression
注释和SpEL表达式,如http://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html所述。
例:
@Controller
@ConditionalOnExpression("${controller.enabled} and ${some.value} > 10")
public class WebController {
从@ConditionalOnProperty
开始,就可以检查多个房产。 name / value属性是一个数组。
@Configuration
@ConditionalOnProperty({ "property1", "property2" })
protected static class MultiplePropertiesRequiredConfiguration {
@Bean
public String foo() {
return "foo";
}
}
对于具有AND检查的简单布尔属性,您不需要@ConditionalOnExpression
。
您可能对Spring Boot 1.3.0中引入的AllNestedConditions
抽象类感兴趣。这允许您创建复合条件,其中您定义的所有条件必须在@Bean
类初始化任何@Configuration
之前应用。
public class ThisPropertyAndThatProperty extends AllNestedConditions {
@ConditionalOnProperty("this.property")
@Bean
public ThisPropertyBean thisProperty() {
}
@ConditionalOnProperty("that.property")
@Bean
public ThatPropertyBean thatProperty() {
}
}
然后你可以像这样注释你的@Configuration
:
@Conditional({ThisPropertyAndThatProperty.class}
@Configuration
通过对两个属性一起使用@ConditionalOnExpression解决了该问题。
@ConditionalOnExpression("'${com.property1}${com.property2}'=='value1value2'")
其中配置中的属性值如下。
物业1名称 - com.property1
价值 - value1
财产2名称 - com.property2
价值 - value2