How to have conditional statement within a spring configuration file
I have String bean (b) whose value depends on the value of a property (a). a is set dynamically based on environment it runs.
if (a)
b="yes"
else
b="no"
How do i code this in spring config?
Annotation Type Conditional The @Conditional annotation may be used in any of the following ways: as a type-level annotation on any class directly or indirectly annotated with @Component , including @Configuration classes. as a meta-annotation, for the purpose of composing custom stereotype annotations.
It allows to load beans conditionally depending on a certain environment property: @Configuration @ConditionalOnProperty( value="module. enabled", havingValue = "true", matchIfMissing = true) class CrossCuttingConcernModule { ... } The CrossCuttingConcernModule is only loaded if the module.
In this tutorial, we'll take a look at the @Conditional annotation. It's used to indicate whether a given component is eligible for registration based on a defined condition.
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.
As Ryan said SpEL can help. You should be able to do something like this in Spring xml:
<bean id="flag" class="java.lang.Boolean">
<constructor-arg value="#{ systemProperties['system.propery.flag'] ?: false }" />
</bean>
<bean id="bean" class="com.my.MyBean">
<property name="property" value="#{ flag ? 'yes' : 'no' }"/>
</bean>
See Spring Expression Language for Spring 3+. Otherwise, you're probably stuck with writing a FactoryBean or something similar.
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