2.4 Reference Injection

So far we have only injected constructor and property values with static values, which is useful if you want to eliminate configuration files. Values can also be injected by reference -- one bean definition can be injected into another. To do this, you use the constructor-arg or property's ref attribute instead of the value attribute. The ref attribute then refers to another bean definition's id.

In the following example, the first bean definition is a java.lang.String with the id springMessage. It is injected into the second bean definition by reference using the property element's ref attribute.

Example 2.4. Reference Setter Injection

Excerpt from chapter02-reference-setter-injection/src/main/resources/applicationContext.xml
                
<bean id="springMessage" 
      class="java.lang.String">
    <constructor-arg value="Spring comes before summer." />
</bean>

<bean id="message"
      class="org.springbyexample.springindepth.chapter02.referenceSetterInjection.Message">
    <property name="message" ref="springMessage" />
</bean>