How to check two condition while using @ConditionalOnProperty or @ConditionalOnExpression

Deadly 提交于 2019-11-30 06:47:15

Use @ConditionalOnExpression annotation and SpEL expression as described here http://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html.

Example:

@Controller
@ConditionalOnExpression("${controller.enabled} and ${some.value} > 10")
public class WebController {
Josh

Since from the beginning of @ConditionalOnProperty it was possible to check more than one property. The name / value attribute is an array.

@Configuration
@ConditionalOnProperty({ "property1", "property2" })
protected static class MultiplePropertiesRequiredConfiguration {

    @Bean
    public String foo() {
        return "foo";
    }

}

For simple boolean properties with an AND check you don't need a @ConditionalOnExpression.

Patrick Grimard

You might be interested in the AllNestedConditions abstract class that was introduced in Spring Boot 1.3.0. This allows you to create composite conditions where all conditions you define must apply before any @Bean are initialized by your @Configuration class.

public class ThisPropertyAndThatProperty extends AllNestedConditions {

    @ConditionalOnProperty("this.property")
    @Bean
    public ThisPropertyBean thisProperty() {
    }

    @ConditionalOnProperty("that.property")
    @Bean
    public ThatPropertyBean thatProperty() {
    }

}

Then you can annotate your @Configuration like this:

@Conditional({ThisPropertyAndThatProperty.class}
@Configuration

Resolved the issue by using @ConditionalOnExpression for the two properties together.

@ConditionalOnExpression("'${com.property1}${com.property2}'=='value1value2'")

Wherein property value in configuration is as below.

Property 1 Name - com.property1 Value - value1

Property 2 Name - com.property2 Value - value2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!