面试之Spring的启动原理 - Java技术债务

引入

为什么突然说一下Spring启动原理呢,因为之前面试的时候,回答的那可谓是坑坑洼洼,前前后后,补补贴贴。。。

总而言之就是不行,再次看一下源码发掘一下。。。

在Spring Boot还没有广泛到家家在用的时候,我们都还在书写繁琐的配置,什么web.xml、spring.xml、bean.xml等等。虽然现在很少,可以说几乎没有企业在去使用Spring的老一套,而会去使用Spring Boot约定大于配置来进行快速开发,但是,Spring的也要去学习,去挖掘,毕竟是我们Java程序员的基础呀。

spring的启动是建筑在servlet容器之上的,所有web工程的初始位置就是web.xml,它配置了servlet的上下文(context)和监听器(Listener)

web.xml


    
        ServletContextListener
        
        com.trace.app.framework.listeners.ApplicationListener
    
    
    
        service_dispatcher
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            /WEB-INF/spring/services/service_dispatcher-servlet.xml
        
        1
    
    
    
        contextConfigLocation
        /WEB-INF/spring/application_context.xml
    
    
    
        
            org.springframework.web.context.ContextLoaderListener
        
    
    
    
        
            com.trace.app.framework.listeners.MySessionListener
        
    

Spring启动过程

spring的上下文监听器


        contextConfigLocation
        /WEB-INF/spring/application_context.xml



        
            org.springframework.web.context.ContextLoaderListener
        
 

spring的启动其实就是IOC容器的启动过程,通过上述的第一段配置 是初始化上下文,然后通过后一段的的来加载配置文件,其中调用的spring包中的ContextLoaderListener这个上下文监听器,ContextLoaderListener是一个实现了ServletContextListener接口的监听器,他的父类是 ContextLoader,在启动项目时会触发contextInitialized上下文初始化方法。

public void contextInitialized(ServletContextEvent event) {
        initWebApplicationContext(event.getServletContext());
}

调用了父类ContextLoader的initWebApplicationContext(event.getServletContext());方法,很显然,这是对ApplicationContext的初始化方法,也就是到这里正是进入了springIOC的初始化。

接下来看一下initWebApplicationContext(event.getServletContext())的工作:

if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
            throw new IllegalStateException(
                    "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");
        }
        long startTime = 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);
            }
            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);
            }

            if (logger.isDebugEnabled()) {
                logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
                        WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
            }
            if (logger.isInfoEnabled()) {
                long elapsedTime = System.currentTimeMillis() - startTime;
                logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
            }

            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;
        }

总结:

  • 创建WebApplicationContext。
  • 加载对应的spring配置文件中的Bean。
  • 将WebApplicationContext放入ServletContext(Java Web的全局变量)中。

接下来,来到了configureAndRefreshWebApplicationContext()方法

作用:

就是用来加载spring配置文件中的Bean实例的。这个方法于封装ApplicationContext数据并且初始化所有相关Bean对象。它会从web.xml中读取名为 contextConfigLocation的配置,这就是spring xml数据源设置,然后放到ApplicationContext中,最后调用传说中的refresh方法执行所有Java对象的创建。

总结: 面试之Spring的启动原理 - Java技术债务

总结

  1. 首先对于一个web应用,需要部署到web容器中,web容器提供了一个全局的上下文环境,ServletContext,SpringIOC的宿主环境。

  2. 其次,在web容器启动时,触发容器初始化,web.xml中提供的有ContextLoaderListener监听器会监听这个事件,初始化方法contextInitialized被调用,初始化spring上下文 WebApplicationContext接口,实现类时XmlWebApplicationContext即SpringIOC容器,对应的Bean定义是有context-param标签定义指定,然后存储到ServletContext中,方便获取。

  3. ContextLoaderListener监听初始化完成后,开始初始化web.xml中配置的Servlet,指DisapatchServlet前端控制器,用来匹配,转发,处理每个Servlet请求,DisaptchServlet初始化时会创建自己的IOC上下文,用来持有Spring MVC的相关bean。 首先会从之前初始化存储在ServletContext中的上下文左右parent上下文,再初始化自己的上下文,大概的工作就是初始化处理器映射、视图解析等。这个servlet自己持有的上下文默认实现类也是xmlWebApplicationContext。然后存储到ServletContext。每个Servlet拥有自己的上下文,也会共享parent的上下文。

下期讲解refresh()做了什么,以及Spring Boot的启动原理,敬请观看,谢谢。。。 下期讲解refresh()做了什么,以及Spring Boot的启动原理,敬请观看,谢谢。。。 下期讲解refresh()做了什么,以及Spring Boot的启动原理,敬请观看,谢谢。。。

   登录后才可以发表评论呦...

专注分享Java技术干货,包括
但不仅限于多线程、JVM、Spring Boot
Spring Cloud、 Redis、微服务、
消息队列、Git、面试题 最新动态等。

想交个朋友吗
那就快扫下面吧


微信

Java技术债务

你还可以关注我的公众号

会分享一些干货或者好文章

Java技术债务