转自:http://www.blogjava.net/liuqiang5151/articles/143499.html
众所周知,Spring框架以对象的依赖注入而著名,通过applicationContext.xml配置,可以实现解耦合。如果我们把所有的对象都通过applicationContext.xml注入,那就会显得很臃肿,难于维护。对此,我们可以采用多配置文件相关联 。比如:在struts-config.xml中如下定义
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> <set-property property="contextConfigLocation" value="/WEB-INF/action-service.xml"/> </plug-in>
在action-service.xml中:
<bean name="/login" class="com.lq.struts.action.LoginAction" abstract="false" lazy-init="default" autowire="default" dependency-check="default">
<property name="userService">
<ref bean="userService" />
</property>
</bean>
在sp-service.xml中
<bean id="userService" class="com.lq.service.impl.UserServiceImpl" lazy-init="default" autowire="default" dependency-check="default">
<property name="userinfoDAO">
<ref bean="userinfoDAO" />
</property>
</bean>
在applicationContext中
<bean id="userinfoDAO" class="com.lq.dao.UserinfoDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
这样也实现了一种分层的思想,易于维护,看起来多爽。最后在web.xml中将其关联
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/sp-service.xml
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class> org.springframework.web.context.ContextLoaderListener </listener-class>
</listener>
注意两点<ref bean="sessionFactory" />不能写成<ref local="sessionFactory" />要不然只能在本文件中找还有每个配置文件的名称空间一定要写。