Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have a couple of options:

Import

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

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


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:

@RunWith(SpringJUnit4ClassRunner.class)
@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:

<context-param> 
    <param-name>contextConfigLocation</param-name>
    <param-value>WEB-INF/conf/spring/this-xml-conf.xml</param-value>
    <param-value>WEB-INF/conf/spring/that-other-xml-conf.xml</param-value>
</context-param>

<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

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" } );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...