1. 程式人生 > >Spring與Struts2整合的執行原理.

Spring與Struts2整合的執行原理.

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屬性的值使用反射建立的物件,如果使用反射無法建立物件,丟擲異常.