broun
broun

Reputation: 2593

Conditional statement inside Spring config

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?

Upvotes: 22

Views: 55227

Answers (4)

Yogi Lal Singh
Yogi Lal Singh

Reputation: 107

below is working for me. system property passed as java -Dflag=true -jar project.jar

<bean id="flag" class="java.lang.Boolean">
  <constructor-arg value="#{ systemProperties['flag'] ?: false }"/>
</bean>

<bean id="bean" class="com.my.MyBean">
  <property name="property" value="#{ flag ? 'yes' : 'no' }"/>
</bean>

Upvotes: 0

RAHUL ROY
RAHUL ROY

Reputation: 136

Try this...It works.. Given Roll,Location,name is in property file and I am reading it above this line.

<bean id="Student" class="beans.Student">
    <property name="name" value="#{ ${Roll}== 1 ? '${Location}' : '${name}' }"/>
</bean>

Upvotes: 3

denis.solonenko
denis.solonenko

Reputation: 11765

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>

Upvotes: 30

Ryan Stewart
Ryan Stewart

Reputation: 128779

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

Upvotes: 2

Related Questions