spring容器启动之我见(二)

来源:互联网 发布:万网域名赎回费用 编辑:程序博客网 时间:2024/05/29 04:54

因为WebApplicationContext 需要ServletContext 实例,也就是说它必须在拥有Web 容器的前提下才能完成启动的工作。有过Web 开发经验的读者都知道可以在web.xml 中配置自启动的Servlet 或定义Web 容器监听器(ServletContextListener),借助这两者中的任何一个,我们就可以完成启动Spring Web 应用上下文的工作。


Spring 分别提供了用于启动WebApplicationContext 的Servlet 和Web 容器监听器:
org.springframework.web.context.ContextLoaderServlet;
org.springframework.web.context.ContextLoaderListener。
两者的内部都实现了启动WebApplicationContext 实例的逻辑,我们只要根据Web 容器的具体情况选择两者之一,并在web.xml 中完成配置就可以了。
你可以查看一下spring3.0的change log 里面注明: 
removedContextLoaderServletand Log4jConfigServlet 的确是去掉了 
spring有三种启动方式,使用ContextLoaderServlet,ContextLoaderListener和ContextLoaderPlugIn
可以采用余下两种启动方式ContextLoaderListener和ContextLoaderPlugIn 建议使用ContextLoaderListener


以下以ContextLoaderListener为例子说明
\

ContextLoaderListener相关配置的注意事项看Spring笔记1——控制反转容器

那通过ContextLoaderListener,Spring是怎么怎么初始化和配置Spring容器(WebApplicationContext)的呢?

Spring容器的初始化过程: \

接下来再详细从代码上介绍吧
ContextLoaderListener的体系结构
\

部署spring例子到tomcat,运行tomcat

\

看到上面spring 和tomcat  结合,我们似乎想到spring和tomcat之间似乎有点什么关系

Tomcat(5.0以上)

加载时的织入配置  Apache Tomcat 缺省的ClassLoader(类装载器)并不支持类的切换, 但是它允许使用用户自定义的类装载器。Spring提供了 TomcatInstrumentableClassLoader 类 (在org.springframework.instrument.classloading.tomcat 包中),这个类继承自Tomcat的类装载器 (WebappClassLoader)并且允许JPA ClassTransformer 的实例来“增强”所有由它加载的类。 简单说,JPA转化器(JPA transformer)仅仅在(使用 TomcatInstrumentableClassLoader 的)特定web应用程序中才能被使用。   

为使用用户自定义的类装载器:   将 spring-tomcat-weaver.jar 复制到 $CATALINA_HOME/server/lib 下 (其中$CATALINA_HOME 表示Tomcat的安装路径)。   

通过修改web application context使Tomcat使用用户自定义的类装载器(而不是默认的类装载器):   

<Context path="/myWebApp" docBase="/my/webApp/location">     

 <Loader loaderClass="org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader"/>  

</Context>


这里开始了ContextLoaderListener的工作了,首先是Spring容器(这里是WebApplicationContext)的初始化
?
1
2
3
4
5
6
7
8
ContextLoader      
      /**
    * Initialize the root web application context.
    */
   @Override
   publicvoidcontextInitialized(ServletContextEvent event) {
       initWebApplicationContext(event.getServletContext());
   }

再看一下ContextLoader的initWebApplicationContext()
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
ContextLoader
publicWebApplicationContext initWebApplicationContext(ServletContext servletContext) {
        if(servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) !=null) {
            thrownewIllegalStateException(
                    Cannot initialize context because there is already a root application context present -  +
                    check whether you have multiple ContextLoader* definitions in your web.xml!);
        }
 
        Log logger = LogFactory.getLog(ContextLoader.class);
        servletContext.log(Initializing Spring root WebApplicationContext);
        if(logger.isInfoEnabled()) {
            logger.info(Root WebApplicationContext: initialization started);
        }
        longstartTime = System.currentTimeMillis();
 
        try{
            // Store context in local instance variable, to guarantee that
            // it is available on ServletContext shutdown.
            if(this.context == null) {
                this.context = createWebApplicationContext(servletContext);      //这里根据ServletContext创建Spring容器(在这里创建的是XmlWebApplicationContext)
            }
            if(this.contextinstanceofConfigurableWebApplicationContext) {
                ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
                if(!cwac.isActive()) {
                    // The context has not yet been refreshed -> provide services such as
                    // setting the parent context, setting the application context id, etc
                    if(cwac.getParent() == null) {
                        // The context instance was injected without an explicit parent ->
                        // determine parent for root web application context, if any.
                        ApplicationContext parent = loadParentContext(servletContext);
                        cwac.setParent(parent);
                    }
                    configureAndRefreshWebApplicationContext(cwac, servletContext);  //这里进行WebApplicationContext的配置工作,其中包括把servletContext和Spring容器关联起来,以及将配置文件(applicationContext.xml)加入到容器中
                }
            }
            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,this.context);
 
            ClassLoader ccl = Thread.currentThread().getContextClassLoader();
            if(ccl == ContextLoader.class.getClassLoader()) {
                currentContext = this.context;
            }
            elseif(ccl != null) {
                currentContextPerThread.put(ccl,this.context);
            }
 
            if(logger.isDebugEnabled()) {
                logger.debug(Published root WebApplicationContext as ServletContext attribute with name [ +
                        WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + ]);
            }
            if(logger.isInfoEnabled()) {
                longelapsedTime = System.currentTimeMillis() - startTime;
                logger.info(Root WebApplicationContext: initialization completed in  + elapsedTime +  ms);
            }
 
            returnthis.context;
        }
        catch(RuntimeException ex) {
            logger.error(Context initialization failed, ex);
            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
            throwex;
        }
        catch(Error err) {
            logger.error(Context initialization failed, err);
            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
            throwerr;
        }
    }

再进入createWebApplicationContext()
?
1
2
3
4
5
6
7
8
9
//ContextLoader
protectedWebApplicationContext createWebApplicationContext(ServletContext sc) {
        Class<!--?--> contextClass = determineContextClass(sc); //返回WebApplicationContext实现类使用,默认XmlWebApplicationContext或如果指定一个自定义上下文类。
        if(!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
            thrownewApplicationContextException(Custom context class[ + contextClass.getName() +
                    ] is not of type [ + ConfigurableWebApplicationContext.class.getName() + ]);
        }
        return(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
    }


再看determineConetxt() width=700

可以看到在这里其实就是根据Parameter CONTEXT_CLASSPARAM去实例化一个WebApplicatoinContext,而该参数其实在web.xml已经配置为XmlWebApplicationContext(WebApplicationContext实现类) ,看web.xml
?
1
2
3
4
5
6
7
8
//web.xml
<!-- 如果配置了contextClass上下文参数,就会用参数所指定的WebApplicationContext实现类初始话容器 -->
  <context-param>
    <param-name>contextClass</param-name>
    <param-value>
    org.springframework.web.context.support.XmlWebApplicationContext
    </param-value>
  </context-param>

接着,我们回到initWebApplicationContext(),其中调用的configureAndRefreshWebApplicationContext(cwac, servletContext);我们看一下他的实现
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
protectedvoidconfigureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
        if(ObjectUtils.identityToString(wac).equals(wac.getId())) {
            // The application context id is still set to its original default value
            // -> assign a more useful id based on available information
            String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);   
            if(idParam != null) {
                wac.setId(idParam);   //这里设置WebApplicationContext的id值为contextId也就是我们浏览器访问的localhost:8080/01/中的01
            }
            else{
                // Generate default id...
                wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
                        ObjectUtils.getDisplayString(sc.getContextPath()));
            }
        }
 
        wac.setServletContext(sc);
        String initParameter = sc.getInitParameter(CONFIG_LOCATION_PARAM);//这里设置Web.xml中配置的contextConfigLocation参数,也就是配置文件applicationContext.xml了
        if(initParameter != null) {
            wac.setConfigLocation(initParameter);
        }
        customizeContext(sc, wac);
        wac.refresh();  //加载刚才的配置文件applicationContext.xml,以及bean的实例化
    }
看一下web.xml中的contextConfigLocation设置吧 \

再看一下
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//XmlWebApplicationContext
@Override
    publicvoidrefresh()throwsBeansException, IllegalStateException {
        synchronized(this.startupShutdownMonitor) {
            // Prepare this context for refreshing.
            prepareRefresh();
 
            // Tell the subclass to refresh the internal bean factory.
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
 
            // Prepare the bean factory for use in this context.
            prepareBeanFactory(beanFactory);
 
            try{
                // Allows post-processing of the bean factory in context subclasses.
                postProcessBeanFactory(beanFactory);
 
                // Invoke factory processors registered as beans in the context.
                invokeBeanFactoryPostProcessors(beanFactory);
 
                // Register bean processors that intercept bean creation.
                registerBeanPostProcessors(beanFactory);
 
                // Initialize message source for this context.
                initMessageSource();
 
                // Initialize event multicaster for this context.
                initApplicationEventMulticaster();
 
                // Initialize other special beans in specific context subclasses.
                onRefresh();
 
                // Check for listener beans and register them.
                registerListeners();
 
                // Instantiate all remaining (non-lazy-init) singletons.
                finishBeanFactoryInitialization(beanFactory);
 
                // Last step: publish corresponding event.
                finishRefresh();
            }
 
            catch(BeansException ex) {
                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();
 
                // Reset 'active' flag.
                cancelRefresh(ex);
 
                // Propagate exception to caller.
                throwex;
            }
        }
    }

这个方法就是配置Spirng Web容器,根据applicationContext.xml实例化类的重中之重了,东西太多了,下篇博客再接着说吧


\
0 0