In a big project we may have several Spring configuration files. One Java bean is defined in one
Spring xml configuration file can be referenced in another configuration file via ref
tag.
The ref tag has the following syntax.
<ref bean="someBean"/>
In the following Spring-Output.xml file we created two Java Beans and gave them id.
<beans ... <bean id="CSVPrinter" class="com.java2s.output.impl.CSVPrinter" /> <bean id="JSONPrinter" class="com.java2s.output.impl.JSONPrinter" /> </beans>
In the following Spring-Common.xml file we defined a com.java2s.output.PrinterHelper Java Bean
and gave it id as PrinterHelper. In order to inject the CSVPrinter
defined in the
Spring-Output.xml file we have to use ref
tag to include it.
<beans ... <bean id="PrinterHelper" class="com.java2s.output.PrinterHelper"> <property name="outputGenerator" > <ref bean="CSVPrinter"/> </property> </bean> </beans>
To reference bean we defined in the same xml file we can use ref
tag with local
attribute.
It has the following format.
<ref local="someBean"/>
In the following xml code, the bean "PrinterHelper" declared in 'Spring-Common.xml' can access "CSVPrinter" or "JSONPrinter" which are defined in the same file with ref local.
<beans ... <bean id="PrinterHelper" class="com.java2s.output.PrinterHelper"> <property name="outputGenerator" > <ref local="CSVPrinter"/> </property> </bean> <bean id="CSVPrinter" class="com.java2s.output.impl.CSVPrinter" /> <bean id="JSONPrinter" class="com.java2s.output.impl.JSONPrinter" /> </beans>
By using ref local we increase the readability of the xml configuration file.