I have been experimenting around with Spring. I wish to copy a bean's value and reference properties for another bean by making use of SpEL.
Consider this bean:
<bean id="kenny" class="com.springinaction.springidol.Instrumentalist">
<property name="song" value="#{'Jingle Bells'}" />
<property name="instrument" ref="piano" />
</bean>
I wish to copy its values into another bean, as shown below:
<bean id="carl" class="com.springinaction.springidol.Instrumentalist">
<property name="song" value="#{kenny.song}" />
<property name="instrument" ref="#{kenny.instrument}" /> <-- I GET EXCEPTION OVER HERE
</bean>
However, I get an exception for the second prpoperty as it does not manage to copy kenny's intrument. The song is copied correctly without any exception being thrown
I get this exception:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'carl' defined in class path resource [Beans.xml]: Cannot resolve reference to bean '#{kenny.instrument}' while setting bean property 'instrument'; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 6): Field or property 'instrument' cannot be found on object of type 'com.springinaction.springidol.Instrumentalist'
Any idea how I can copy the instrument and set it for the bean with id "carl" please?
A ref
is a reference to another bean; in your case you want to use the value of the instrumemt
property of the kenny
bean.
You should use
<property name="instrument" value="#{kenny.instrument}" />
This assumes there is a getInstrument()
method on Instrumentalist
.