Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional statement inside Spring config

Tags:

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?

like image 684
broun Avatar asked Aug 02 '11 03:08

broun


People also ask

What is @conditional annotation in spring?

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.

How do I load a spring conditionally bean?

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.

What is @conditional in spring boot?

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.

How do I remove Spring beans based on specific conditions?

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.


2 Answers

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>
like image 152
denis.solonenko Avatar answered Sep 22 '22 18:09

denis.solonenko


See Spring Expression Language for Spring 3+. Otherwise, you're probably stuck with writing a FactoryBean or something similar.

like image 20
Ryan Stewart Avatar answered Sep 22 '22 18:09

Ryan Stewart