spring 之ActionServlet代理

    技术2022-05-11  109

        spring 在structs 框架下对actionservlet的代理是通过在struct-config.xml植入spring plug-in来对action 进行托管的。那究竟spring在plug-in中做了哪些动作使得自己的配置文件springapplication.xml可以托管structs的action呢?     在struct-config.xml中,spring plug-in的配置一般如下: <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"    <set-property property="contextConfigLocation"                            value="/WEB-INF/applicationContext.xml" />  </plug-in>

    org.springframework.web.struts.ContextLoaderPlugIn 实现了org.apache.struts.action.PlugInPlugIn的destroy()方法被实现用来关闭对actionservlet的控制,init()则被实现用来初始化spring配置.对action的托管是在init方法内实现的:/**  * Create the ActionServlet's WebApplicationContext.  */public final void init(ActionServlet actionServlet, ModuleConfig moduleConfig)     throws ServletException {

           this.actionServlet = actionServlet;       this.moduleConfig = moduleConfig;       try {            //spring主要在这边进行配置            this.webApplicationContext = initWebApplicationContext();             onInit(); //该方法什么都没做       }       catch (RuntimeException ex) {       logger.error("Context initialization failed", ex);       throw ex;  }}

    转向到initWebApplicationContext() :WebApplicationContext parent = WebApplicationContextUtils.getWebApplicationContext(getServletContext());WebApplicationContext wac = createWebApplicationContext(parent);

    WebApplicationContext是spring web mvc的web应用程序(bean)的控制器,类比于servlet2.4中的servletContext.getServletContext() 方法获取了structs的 actionservlet(通过实现init方法可以得到)的ServletContext,也就是serlvet控制器.initWebApplicationContext() 最终是通过createWebApplicationContext()返回了spring的servletcontext,从此获得actionservlet的代理权.它将action当做spring中一个普通的bean进行管理。

         看来还得再看下createWebApplicationContext()做了哪些事了:我们先看下它的注释怎么解释的:

    /**  * Instantiate the WebApplicationContext for the ActionServlet, either a default  * XmlWebApplicationContext or a custom context class if set. This implementation  * expects custom contexts to implement ConfigurableWebApplicationContext.  * Can be overridden in subclasses.  */

    该方法重要流程如下:

    1、初始化配置文件解析类:缺省的类为:XmlWebApplicationContext,该类定义的默认的文件路径: "/WEB-INF/applicationContext.xml"用来查找配置文件。

    2、通过调用org.springframework.web.context.ConfigurableWebApplicationContext 类的setParent(ApplicationContext parent)达到支持多配置文件的目的(比如我们在strcts中配置了多个spring plug-in ,它们可以使用不同的xml文件),注意的是ConfigurableWebApplicationContext 类实例化(通过对XmlWebApplicationContext进行强制类型转换)后默认的配置文件为XmlWebApplicationContext中定义好的"/WEB-INF/applicationContext.xml。如果在structs-confg.xml中相应的plug-ini没有对contextConfigLocation  属性进行配置的话,将使用默认的文件名和路径。

    3、在WebApplicationContext 加入BeanFactoryPostProcessor,把所需要托管的actionservlet加入到spring的bean处理容器内。

    4、通过ConfigurableWebApplicationContext 的refresh()方法把前面配置好的WebApplicationContext载入spring web容器内。

     

    最新回复(0)