How to check two conditions when using @ConditionalOnProperty or @ConditionalOnExpression

I need to check two conditions ('AND' (both conditions must be met)) in the yml file when creating the bean. How to do this because @ConditionalOnProperty only supports one property configuration.

+4
source share
4 answers

You might be interested in the abstract class AllNestedConditions , which was introduced in Spring Boot 1.3.0. This allows you to create complex conditions when all the conditions that you define must be applied before any @Bean is 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 as follows:

 @Conditional({ThisPropertyAndThatProperty.class} @Configuration 
+4
source

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 AND checking, you do not need @ConditionalOnExpression.

+4
source

Use the @ConditionalOnExpression annotation and the @ConditionalOnExpression 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 { 
+2
source

Fixed issue with @ConditionalOnExpression for two properties together.

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

The property value in the configuration is shown below.

Property 1 Name - com.property1 Value - value1

Property 2 Name - com.property2 Value - value2

0
source

Source: https://habr.com/ru/post/1259434/


All Articles