I'm using Spring-Boot-1.1.7. My intention is to add a bean to my context according to a value of a property of type string.
I mean, I can see a lot of examples of boolean values such as this:
@ConditionalOnExpression("${xxx.enabled:true}")
But I want an expression based on a value of a property, for example:
@ConditionalOnExpression("${server.host==localhost} or ${server.port==8080} ")
or something like that.
Can someone show me an example how to do it?
The Spring framework provides the @ConditionalOnProperty annotation precisely for this purpose. In short, the @ConditionalOnProperty enables bean registration only if an environment property is present and has a specific value. By default, the specified property must be defined and not equal to false.
Why do we need Conditional Beans? A Spring application context contains an object graph that makes up all the beans that our application needs at runtime. Spring's @Conditional annotation allows us to define conditions under which a certain bean is included into that object graph.
The @ConditionalOnExpression annotation lets configuration be included based on the result of a SpEL (Spring Expression Language) expression. For this example the Module class is only loaded if a particular SpEL is enabled.
In Spring Boot, you can use the @ConditionalOnProperty annotation to enable or disable a particular bean based on the presence of a property. This is very useful if you want to provide optional features to your microservice. And that's it. Your optionalClass bean should resolve to null when you specify mybean.
Eventually , this one worked for me:
@ConditionalOnExpression("'${server.host}'=='localhost'")
For property value conditional I used:
@ConditionalOnProperty(name="server.host", havingValue="localhost")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With