Spring 容器都应该在应用启动时自动力口载。为了让Spring 容器能自动加载,通常有以下两种做法:
·让MVC 框架负责创建ApplicationContext 实例,并在MVC 框架加载时自动创建Spring 容器。Struts 就是采用这种机制与Spring 整合。
·在web.xml 文件中加载Spring 容器,这是最常见的做法。Spring 自己的MVC 框架就是采用这种策略。
对于在web.xml 配置文件中配置ApplicationContext 的自动创建有两种策略:
.利用ServletContextListener 实现。
·采用load-on-startup Servlet 实现。
根据Servlet 2.3 标准,所有的ServletContextListener 都会比Servlet 优先加载,即使是load-on-startup Servlet
Spring 提供Sery letContextListener 的一个实现类Context Lo aderListener ,该类可以作为listener 使用,它会在创建时自动查找WEB-INF/ 下的applicationContext.xrnl 文件。因此,如果只有一个配置文件,并且文件名为applicationContex t. xrnl ,则只需在web.xrnl文件中增加如下代码即可:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-工NF/daoContext.xml,/WEB-INF/spring/applicationContext.xml</param-value>
</context-param>
<1istener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
获取ApplicationContext 实例:
WebApplicat工onContext ctx = WebApplicationContextUti
采用load-on-startup Servlet 创建AppiicationContext
<servlet>
<servlet-name>context</servlet-nane>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>l</load-on-startup>
</servlet>
为了让Action访问Spring 的业务逻辑组件,有以下两种策略:
• Spring 管理控制器,并利用依赖注入为控制器注入业务逻辑组件。
·控制器显式定位Spring 工厂,也就是Spring 容器的App1icationContext 实例,从工厂中获取业务逻辑组件实例的引用。
ContextLoaderPlugin
<plug-in className="org.springframework.web.struts.ContextLoaderPlugln">
<set-property property="contextConfigLocation" value="/WEB-INF/action-servlet.xnl , /WEB-NF/applicationContext.xml"/>
</plug-in>
需要让ActionServlet 将请求不再转发给struts-config.xrnl 配置的action ,而是转发给
ApplicationContext 里配置的bean 。
ActionServlet 将请求转发到Spring 容器,有以下两个时机。
- 在ActionServlet 之处将处理转发给Spring 容器中的bean
- 在Action 之处将处理转发给Spring 容器中的bean
根据这两个时机,完成这个转发也有以下两种策略。
- 采用DelegatingRequestProcess
or ,在ActionServlet 处完成转发。 - 采用DelegatingActionProxy ,在Action 处完成转发。
使用DelegatingRequestProcess
//使用spring 的RequestProcessor 替换struts 原有的RequestProcessor
<controller processorClass="org.springframework.web.struts.DelegatingRequestProcess
使用DelegatingActionProxy
而DelegatingActionProxy 则被配置成Struts 的action ,即所有的请求先被ActionServlet 拦截,然后将请求转发到对应的action ,而action的实现类全都是DelegatingActionProxy; 最后由DelegatingActionProxy 将请求转发给Spring 容器的bean 。