TomCat 启动 –>加载web.xml文件;
在web.xml文件中
配置了Spring的监听器,这个实现的是ServletContextListener接口,那么当Web容器启动的时候,这个监听器就会执行.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<!-- 该参数是描述Spring配置文件的位置 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext.xml</param-value>
</context-param>
/*1、该配置可以不写,默认加载WEB-INF/applicationContext.xml
2、该配置可以这么写WEB-INF/*Context.xml,WEB-INF/application*.xml
这么写不利于测试
3、就是上面的写法,推荐
*/
web容器启动时执行监听器ContextLoaderListener 中的初始化方法contextInitialized().
1.这个方法创建了SpringWeb容器, springWeb容器根据web.xml中的param参数来加载配置文件.实例化配置文件中的类(dao层和service层).
2.把创建出来的SpringWeb容器放入ServletContext中,key值为WebApplicationContext.Root
可以通过这种形式得到spring的web容器:
WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext servletContext);
struts2的默认配置文件struts-default.xml中:
<bean type="com.opensymphony.xwork2.ObjectFactory" name="struts" class="org.apache.struts2.impl.StrutsObjectFactory" />
Action是由StrutsObjectFactory来创建的,现在我们需要把创建Action的任务交给Spring来做,
在struts2和spring框架整合的jar包struts2-spring-plugin-2.3.1.2.jar中, 有一个struts.xml的配置文件,内容如下:
struts-plugin.xml
<bean type="com.opensymphony.xwork2.ObjectFactory" name="spring" class="org.apache.struts2.spring.StrutsSpringObjectFactory" />
<constant name="struts.objectFactory" value="spring" />
此配置文件将struts2创建action的方法由StrutsObjectFactory 更改为StrutsSpringObjectFactory来创建action.
在配置Action的时候,在class属性中描述的是在Spring中配置的Action的id.
<action name="personAction_*" method="{1}" class="personAction">
收到一个请求,Struts2过滤器开始执行.当执行到DefaultInvocation调用init方法.
ObjectFactory中的buildAction方法创建action;
ObjectFactory:StrutsSpringObjectFactory.buildAction();
先根据class属性的值从spring容器中获取action,返回对象.如果没有找到,则返回根据class属性的值使用反射创建的对象,如果使用反射无法创建对象,抛出异常.