一、MVC框架創建ApplicationContext實例,在MVC框架加載時自動創建SPRING容器。
1、由spring容器管理action兩種方式:
通過contextConfigLocation屬性載入,多個配置文件則用","隔開。
- <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
- <set-property property="contextConfigLocation" value="/WEB-INF/classes/applicationContext.xml" />
- </plug-in>
·DelegatingRequestProcessor
- <controller>
- <set-property property="processorClass"
- value="org.springframework.web.struts.DelegatingRequestProcessor" />
- </controller>
·DelegatingActionProxy
修改action的type屬性爲:
type="org.springframework.web.struts.DelegatingActionProxy"
2、ActionSupport代替Action使action在程序中手動獲得
在Action中訪問ApplicationContext兩種方法:
·WebApplicationContextUtils工具類
通過ServletContext獲得spring容器實例。
·ActionSupport支持類
通過getWebApplicationContext()方法獲取ApplicationContext實例。
二、在web.xml文件中加載SPRING容器
兩種策略:
1、ServletContextListener實現
支持Servlet 2.3以及以上
·只有一個配置文件applicationContext.xml
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
·有多個配置文件applicationContext.xml daoContext.xml
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/daoContext.xml,/WEB-INF/applicationContext.xml</param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
2、load-on-startup Servlet實現
不支持Servlet 2.3
·只有一個配置文件applicationContext.xml
- <servlet>
- <servlet-name>context</servlet-name>
- <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
·有多個配置文件applicationContext.xml daoContext.xml
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/daoContext.xml,/WEB-INF/applicationContext.xml</param-value>
- </context-param>
- <servlet>
- <servlet-name>context</servlet-name>
- <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>