SpringMVC源码阅读:ContextLoaderListe

2018-11-19  本文已影响0人  飞狗未来

1 概述

2 web.xml配置

ContextLoaderListener监听器的作用就是启动web容器时,自动装配ApplicationContext的配置信息。它实现了ServletContextListener接口,在web.xml文件中配置这个监听器,Tomcat或Jetty启动容器时,就会默认执行它实现的方法。

<!-- 配置spring IOC参数路径 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/spring-context*.xml</param-value>
    </context-param> 
<!-- Spring监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-    
         class>
    </listener>

通过扩展ContextLoaderListener类,可以增加初始化时的个性化功能,如输出产品的信息等。

3 获取WebApplicationContext的实现类

在org.springframework.web.context.ContextLoader中有一个静态属性,

static {
        // Load default strategy implementations from properties file.
        // This is currently strictly internal and not meant to be customized
        // by application developers.
        try {
            ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
            defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
        }
        catch (IOException ex) {
            throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
        }
    }

默认的DEFAULT_STRATEGIES_PATH=ContextLoader.properties,路径在ContextLoader类的同一级目录下,都在spring-web-..*.RELEASE.jar包内。ContextLoader.properties的内容为:

# Default WebApplicationContext implementation class for ContextLoader.
# Used as fallback when no explicit context implementation has been specified as context-param.
# Not meant to be customized by application developers.

org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext

实际的实例化为org.springframework.web.context.support.XmlWebApplicationContext。

4 初始化WebApplicationContext

Tomcat的ApplicationContextFacade对象是SpringIOC根容器的父容器,是ApplicationContextFacade对象的一个属性,属性值为WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE


初始化WebApplicationContext

createWebApplicationContext(servletContext)的实现

image.png
<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/spring-context*.xml</param-value>
    </context-param>

refresh()方法

所在类org.springframework.context.support.AbstractApplicationContext

public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // 准备context的刷新,设置启动日期和活动标识,执行资源文件的初始化
            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) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Exception encountered during context initialization - " +
                            "cancelling refresh attempt: " + ex);
                }

                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();

                // Reset 'active' flag.
                cancelRefresh(ex);

                // Propagate exception to caller.
                throw ex;
            }
        }
    }

知识点

上一篇下一篇

猜你喜欢

热点阅读