拆分成多个以后,bean的配置可以放在其中一个文件中,不必在每个文件中都复制。
多个文件,比如applicationContext-datasource.xml(数据源的)、applicationContext- hibernate.xml、applicationContext-service.xml
你只需要在web.xml中配置:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext-*.xml
</param-value>
</context-param>
这样spring就可以把多个文件同时装载。
同样在struts-config.xml中也可以实现:
<plug-in
className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/classes/Spring-model-config.xml,/WEB-INF/classes/Spring-web-config.xml" />
</plug-in>
以插件的形式加载多个配置文件。
事实上它们的原理都一样,只要内存中有了想要的Bean就可以了。
在一个配置文件中的bean想要引用另一个文件中的bean,可以使用
<property name="dataSource"><ref bean="dataSource"/></property>
这样拿到。注意是bean=,而不是local=。
如果是使用local=表示从当前配置文件中寻找bean,如果bean是在其他文件中则用bean=来找。
总结:最好保持一个applicationContext.xml的原配置文件,并在原文件中导入其它配置文件,这样可以方便调用所有的bean,比如在测试时候可以context = new ClassPathXmlApplicationContext("applicationContext.xml");加载所有bean。