Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to check that two conditions are satisfied on a YAML property file, while creating a bean. How do I do that, as the @ConditionalOnProperty annotation supports only one property?

like image 919
Zenith Kenneth Avatar asked Mar 15 '16 16:03

Zenith Kenneth


3 Answers

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.

like image 112
Josh Avatar answered Oct 24 '22 07:10

Josh


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 {
like image 34
Navrocky Avatar answered Oct 24 '22 07:10

Navrocky


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
like image 10
Patrick Grimard Avatar answered Oct 24 '22 09:10

Patrick Grimard