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.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="springMessage" class="java.lang.String"> <constructor-arg value="Spring is fun." /> </bean> <bean id="message" class="org.springbyexample.di.xml.SetterMessage"> <property name="message" ref="springMessage" /> </bean> </beans>