Spring Boot SpEL ConditionalOnExpression checks several properties

How can i use

For example, checking that one property is true will use the syntax:

@ConditionalOnExpression("${property.from.properties.file}") 

What will be the syntax for checking property1 == true && property2 == false ? If the properties can have different values.

The answer to a similar question: How to check two conditions when using @ConditionalOnProperty or @ConditionalOnExpression concatenates two lines together and performs the check as follows:

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

This syntax seems confusing for someone reading this code, and it seems like a hacker solution. I want to find the right way to test two separate properties without concatenating values.

Also, to be clear, the answer is not what you can easily find from what I saw. It seemed like a very simple answer, but it turned out to be pretty elusive.

+5
source share
2 answers

The @ConditionalOnProperty and @ConditionalOnExpression annotations do not have java.lang.annotation.Repeatable annotations, so you cannot just add multiple annotations to check for multiple properties.

The following syntax has been tested and works:

Solution for two properties

 @ConditionalOnExpression("${properties.first.property.enable:true} && ${properties.second.property.startServer:false}") 

Please note the following:

  • You need to use a colon to indicate the default property in the expression language expression
  • Each property is in a separate language block of the expression $ {}
  • && operator used outside SpEL blocks

It allows you to use multiple properties with different values ​​and can apply to multiple properties.

If you want to check more than two values ​​and still maintain readability, you can use the concatenation operator between the various conditions that you evaluate:

Solution for more than 2 properties

 @ConditionalOnExpression("${properties.first.property.enable:true} " + "&& ${properties.second.property.enable:true} " + "&& ${properties.third.property.enable:true}") 

The downside is that you cannot use the matchIfMissing argument, as you could use the @ConditionalOnProperty annotation, so you will need to make sure that the properties are present in the .properties or YAML files for all your profiles / environments or just rely on the default value

+4
source

As far as I remember, you can use this expression:

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

for further reading link here

If this was helpful, make a comment so that my confusion can also be cleared.

+1
source

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


All Articles