spirng-mvc之ContextLoaderListener启动流程

Spring在Web应用中使用时需要配置一个启动入口,也即org.springframework.web.context.ContextLoaderListener监听器,下面我们来看看源码:

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
    ...
    @Override
    public void contextInitialized(ServletContextEvent event) {
        initWebApplicationContext(event.getServletContext());
    }
}

initWebApplicationContext(...)方法是继承父类org.springframework.web.context.ContextLoader的方法,接着来看这个方法:我省略了不必要的日志等代码

public class ContextLoader {
    ...
    @Nullable
    private WebApplicationContext context;
    
    public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
        try {
            // Store context in local instance variable, to guarantee that
            // it is available on ServletContext shutdown.
            if (this.context == null) {
                this.context = createWebApplicationContext(servletContext);
            }
            if (this.context instanceof ConfigurableWebApplicationContext) {
                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);
                }
            }
            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
    
            ClassLoader ccl = Thread.currentThread().getContextClassLoader();
            if (ccl == ContextLoader.class.getClassLoader()) {
                currentContext = this.context;
            }
            else if (ccl != null) {
                currentContextPerThread.put(ccl, this.context);
            }
            return this.context;
        }
        catch (RuntimeException ex) {
            logger.error("Context initialization failed", ex);
            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
            throw ex;
        }
        catch (Error err) {
            logger.error("Context initialization failed", err);
            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
            throw err;
        }
    }
}

这里我们直接进入ContextLoader#createWebApplicationContext()方法,其他的细节先放下:

protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
    Class<?> contextClass = determineContextClass(sc);
    if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
        throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
                "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
    }
    return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}

其中determineContextClass()方法的作用是判断ApplicationContext的具体子类类型,如果不是ConfigurableWebApplicationContext的子类,就抛出异常。我们来看看Spring是如何判断的:

protected Class<?> determineContextClass(ServletContext servletContext) {
    String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
    if (contextClassName != null) {
        try {
            return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
        }
        catch (ClassNotFoundException ex) {
            throw new ApplicationContextException(
                    "Failed to load custom context class [" + contextClassName + "]", ex);
        }
    }
    else {
        contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
        try {
            return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
        }
        catch (ClassNotFoundException ex) {
            throw new ApplicationContextException(
                    "Failed to load default context class [" + contextClassName + "]", ex);
        }
    }
}

一般情况下,我们最终的实现是org.springframework.web.context.support.XmlWebApplicationContext这个类型,等下我们直接分析这个类型的实例化。接下来才是真正实例化ApplicationContext:BeanUtils.instantiateClass(contextClass),这句代码本身没什么,当前的结果就是调用contextClass的构造函数实例化这个类型。有关BeanUtils的介绍看看这篇文章《Spring的BeanUtils原理》。所以现在我们的方向就转移到了ApplicationContext的构造函数了。在这之前我们需要先看看ApplicaitonContext相关的类图:

可以看到ConfigurableWebApplicationContext的实现还是挺多的, 下面我们直接看org.springframework.web.context.support.XmlWebApplicationContext这个类是如何实例化的。走读源码发现XmlWebApplicationContext类里面没有写无参构造,所以肯定调用了父类的无参构造:

public abstract class AbstractRefreshableWebApplicationContext extends AbstractRefreshableConfigApplicationContext implements ConfigurableWebApplicationContext, ThemeSource {
    public AbstractRefreshableWebApplicationContext() {
        setDisplayName("Root WebApplicationContext");
    }
}

父类的无参构造也没做什么,继续看

public abstract class AbstractRefreshableConfigApplicationContext extends AbstractRefreshableApplicationContext implements BeanNameAware, InitializingBean {
    public AbstractRefreshableConfigApplicationContext() {
    }
}

继续看父类:

public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext {
    public AbstractRefreshableApplicationContext() {
    }
}

继续看父类:

public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
    public AbstractApplicationContext() {
        this.resourcePatternResolver = getResourcePatternResolver();
    }
}

这里就指定了ResourcePatternResolver,关于ResourcePatternResolver的说明,看这篇文章《Spring中Resource和ResourceLoader》,这些并不是加载Bean的工作,我们还得继续看ContextLoader#initWebApplicationContext()方法,里面重要得方法是:

protected void configureAndRefreshWebApplicationContext(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);
        }
        else {
            // Generate default id...
            wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
                    ObjectUtils.getDisplayString(sc.getContextPath()));
        }
    }

    wac.setServletContext(sc);
    String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
    if (configLocationParam != null) {
        wac.setConfigLocation(configLocationParam);
    }

    // The wac environment's #initPropertySources will be called in any case when the context
    // is refreshed; do it eagerly here to ensure servlet property sources are in place for
    // use in any post-processing or initialization that occurs below prior to #refresh
    ConfigurableEnvironment env = wac.getEnvironment();
    if (env instanceof ConfigurableWebEnvironment) {
        ((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
    }

    customizeContext(sc, wac);
    wac.refresh();
}

下面得wac.refresh()方法跳转到了AbstractApplicationContext#refresh():

public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        // Prepare this context for refreshing.
        // 1
        prepareRefresh();
        // Tell the subclass to refresh the internal bean factory.
        // 2
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
        // Prepare the bean factory for use in this context.
        // 3
        prepareBeanFactory(beanFactory);
        try {
            // Allows post-processing of the bean factory in context subclasses.
            // 4
            postProcessBeanFactory(beanFactory);
            // Invoke factory processors registered as beans in the context.
            // 5
            invokeBeanFactoryPostProcessors(beanFactory);
            // Register bean processors that intercept bean creation.
            // 6
            registerBeanPostProcessors(beanFactory);
            // Initialize message source for this context.
            // 7
            initMessageSource();
            // Initialize event multicaster for this context.
            // 8
            initApplicationEventMulticaster();
            // Initialize other special beans in specific context subclasses.
            // 9
            onRefresh();
            // Check for listener beans and register them.
            // 10
            registerListeners();
            // Instantiate all remaining (non-lazy-init) singletons.
            // 11
            finishBeanFactoryInitialization(beanFactory);
            // Last step: publish corresponding event.
            // 12
            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;
        }
        finally {
            // Reset common introspection caches in Spring's core, since we
            // might not ever need metadata for singleton beans anymore...
            resetCommonCaches();
        }
    }
}

可以看到整个流程得步骤非常清晰,我们就来一一看看这个流程。可以看到,有很多工作是关于BeanFactory的,说明ApplicationContext实例化的一大部分工作就是创建BeanFactory。我们先来大致看看这几个方法的作用,上面我做了顺序标记,我们一步步来看,
第1步:prepareRefresh()方法:
1、记录启动时间戳和启动状态标记;
2、初始化environment中占位配置文件;
3、检验environment中配置文件属性;

第2步:obtainFreshBeanFactory()方法:

1、重新获取BeanFactory,创建所有Bean的BeanDifinition

第3步:prepareBeanFactory()方法:

1、将BeanFactory里的其他属性赋值

第4步:postProcessBeanFactory()方法:

1、BeanFactory的后处理

第5步:invokeBeanFactoryPostProcessors()方法:

1、调用实现BeanFactoryPostProcess接口的方法,查看相关《BeanFactoryPostProcessor》

第6步:registerBeanPostProcessors()方法:

1、注册BeanPostProcessor

第7步:initMessageSource()方法:

1、实例化MessageSource接口的一个实现类。这个接口提供了消息处理功能。

第8步:initApplicationEventMulticaster()方法:

1、初始化事件广播器

第9步:onRefresh()方法:

1、初始化其他特殊的bean。其实就是初始化ThemeSource接口的实例。这个方法需要在所有单例bean初始化之前调用。

第10步:registerListeners()方法:

1、检查监听器bean并实例化他们

第11步:finishBeanFactoryInitialization()方法:

1、这一步将初始化所有非懒加载的单例bean,是很重要的一步,也是和编程人员联系最紧密的一步,类型的实例化,调用BeanPostProcessor都是这里处理的。第二步中只是完成了BeanDefinition的定义、解析、处理、注册。但是还没有初始化bean实例。

第12步:finishRefresh()方法:

1、发布通信事件,告知监听者。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值