ohseekay
ohseekay

Reputation: 805

Spring - how to reference another property within the same bean?

I have the following definition in my configuration:

<bean class="com.project.TimerBean">
    <property name="delay" value="30000" />
    <property name="interval" value="60000" />
    <property name="invokeThis" value="com.project.TargetClass" />
    <property name="receiver" value="XYZ" />
    <property name="args" value="#{interval}" />
</bean>

I would like to set the value of args to the same value as interval (in this case, 60000) without having to hard-code the value. However, the above snippet doesn't seem to work. How should I change this?

Upvotes: 2

Views: 3708

Answers (2)

Alex
Alex

Reputation: 11579

Move interval value "60000" to the property file

yourVariableName = 60000

and change to:

<property name="interval" value="${yourVariableName}" />
<property name="args" value="${yourVariableName}" />

Upvotes: 0

yaswanth
yaswanth

Reputation: 2477

# syntax (Spel Expressions) are supposed to work the way you wrote it. You need to replace

#{interval} to #{beanId.interval}.

For example, if the id of the bean you are creating is timerBean, #{timerBean.interval} is supposed to work. You cannot refer to a property directly even if it is a part of the bean definition.

It only works if the property you are referring to is a part of another bean.

<bean id="beanA" class="org.BeanA">
  <property name="prop1" value="1000" />
</bean>

<bean id="beanB" class="org.BeanB">
  <property name="prop2" value = "#{beanA.prop1}" />
  <property name="prop3" value = "#{beanB.prop2}" />
</bean>

In the above example, prop2 gets initialised from prop1 correctly. But prop3 gets initialised to null.

If you look at AbstractAutowireCapableBeanFactory class and method,

protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs)

you can see that all the property values in a single bean definition are looped over and values are parsed. After all the values have been successfully parsed, only then they are set on the bean instance. In the above beanA and beanB example when prop3's value is getting parsed, spring looks for the value of prop2 on beanB which is not yet set and hence returns null.

AFAIK, there is no way around this except the way suggested by @Alex

PS: I am using spring version 4.1.6.RELEASE

Upvotes: 1

Related Questions