Jeffrey.W.Dong Jeffrey.W.Dong - 1 year ago 195
Java Question

how to reference a bean of another xml file in spring

I have a Spring bean defined in an xml file. I want to reference it from another xml file. How can I go about it?

Answer Source

You have a couple of options:


<import resource="classpath:config/spring/that-other-xml-conf.xml"/>

<bean id="yourCoolBean" class="org.jdong.MyCoolBean">
    <property name="anotherBean" ref="thatOtherBean"/>

Include in the ApplicationContext Construction

Make both files a part of your ApplicationContext when you create it => then no import is needed.

For example if you need it during testing:

@ContextConfiguration({ "classpath:META-INF/conf/spring/this-xml-conf.xml",
                    "classpath:META-INF/conf/spring/that-other-xml-conf.xml" })
public class CleverMoneyMakingBusinessServiceIntegrationTest {...}

In case it is a web app, you'd do it in web.xml:



If it is a stand alone app, library, etc.. you would load your ApplicationContext as:

new ClassPathXmlApplicationContext( 
    new String[] { "classpath:META-INF/conf/spring/this-xml-conf.xml",
                   "classpath:META-INF/conf/spring/that-other-xml-conf.xml" } );