Spring – Bean reference example
In Spring, beans can access to each other by specify the bean references in the same or different bean configuration file.
Bean in different XML file
<ref bean="someBean"/>If you are referring to a bean in the different XML file, you can use the ‘ref’ tag with ‘bean’ attribute. In this example, the bean declared in ‘Spring-Common.xml’ can access any beans in ‘Spring-Output.xml’ by using a ‘ref’ attribute in property tag.
Spring-Common.xml
<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-2.5.xsd"> <bean id="OutputHelper" class="com.mkyong.output.OutputHelper"> <property name="outputGenerator" > <ref bean="CsvOutputGenerator"/> </property> </bean> </beans>
Spring-Output.xml
<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-2.5.xsd"> <bean id="CsvOutputGenerator" class="com.mkyong.output.impl.CsvOutputGenerator" /> <bean id="JsonOutputGenerator" class="com.mkyong.output.impl.JsonOutputGenerator" /> </beans>
Bean in same XML file
<ref local="someBean"/>If you are referring to a bean in the same XML file, you should use the ‘ref’ tag with ‘local’ attribute. In this example, the beans declared in ‘Spring-Common.xml’ can access to each other.
Spring-Common.xml
<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-2.5.xsd"> <bean id="OutputHelper" class="com.mkyong.output.OutputHelper"> <property name="outputGenerator" > <ref local="CsvOutputGenerator"/> </property> </bean> <bean id="CsvOutputGenerator" class="com.mkyong.output.impl.CsvOutputGenerator" /> <bean id="JsonOutputGenerator" class="com.mkyong.output.impl.JsonOutputGenerator" /> </beans>
Conclusion
Actually, the ‘ref’ can access to a bean either in same or different XML files, however, for the project readability, you should use the ‘local’ attribute if you reference to a bean which declared in the same XML file.


