读spring源码__容器初始化

读spring源码__容器初始化

今天第一天开始读spring源码,是自己边学边做笔记,所以可能更新的比较慢也有可能更新的不全,如果又不严谨的地方忘多指教,以后的路要一起走哦。
从web.xml中配置的ContextLoaderListener着手,因为WebApplicationContext 需要ServletContext 实例,也就是说它必须在拥有Web 容器的前提下才能完成启动的工作。有过Web 开发经验的读者都知道可以在web.xml 中配置自启动的Servlet 或定义Web 容器监听器

1.1代码入口

断点调试进入ContextLoaderListener的contextInitialized方法中

    public void contextInitialized(ServletContextEvent event) {
        this.contextLoader = createContextLoader();
        if (this.contextLoader == null) {
            this.contextLoader = this;
        }
        this.contextLoader.initWebApplicationContext(event.getServletContext());//初始化容器
    }

其中较为重要的是initWebApplicationContext()方法,将这个方法F5进去看看。

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
        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);//这里根据ServletContext创建Spring容器(在这里创建的是XmlWebApplicationContext)  
            }
            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);//这里进行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;
            }
            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;//返回创建的XmlWebApplicationContext
        }
        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;
        }
    }

首先判断servletcontext上下文环境中是否有WebApplicationContext.ROOT这个属性attribute,一个应用只能有一个容器,有则抛出状态不合法异常,即保证在web.xml中只能有一个ContextLoader。在createWebApplicationContext方法中创建WebApplicationContext。下面是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是返回一个WebApplicationContext的实现类,获取web.xml中的contextclass实例化一个WebApplicationContext对象,这里指的是xmlWebApplicationContext。如果servletContext对象中即web.xml没有初始化该参数,则在ContextLoader.properties配置文件中得到WebApplicationContext属性的className继而反射得到该类的对象WebApplicationContext对象。代码如下:
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
  • 如果contextClass不是ConfigurableWebApplicationContext的超类或接口,则抛出ApplicationContextException异常,否则,则创建该对象并强转为ConfigurableWebApplicationContext对象返回。

  • 这里 BeanUtils.instantiateClass( contextClass ) 用来创建该对象,在内部还作了构造器是否public以及传过来的类是否是接口的判断等判断逻辑。

  • 回到 initWebApplicationContext 方法中,刚才返回了一个ConfigurableWebApplicationContext的对象,判断该对象类型后进入,isActive 是用来做异步处理的,parent为空表示上下文尚未刷新- >提供服务,如设置父上下文中,设置应用程序上下文id等等。loadParentContext(servletContext)方法返回一个BeanFactoryLocator对象,将初始化好的context设置给servletContext的WebApplicationContext.ROOT属性。并将初始化好的context返回。

  • 再看看initWebApplicationContext方法中configureAndRefreshWebApplicationContext方法的实现
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);//这里设置WebApplicationContext的id值为contextId也就是我们浏览器访问的localhost:8080/01/中的01  
            }
            else {
                // Generate default id...
                if (sc.getMajorVersion() == 2 && sc.getMinorVersion() < 5) {
                    // Servlet <= 2.4: resort to name specified in web.xml, if any.
                    wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
                            ObjectUtils.getDisplayString(sc.getServletContextName()));
                }
                else {
                    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的实例化 
    }
  • Spring容器的初始化过程
    Spring容器的初始化过程

下面就是Bean的初始化过程了即IOC控制反转,请看下一章。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值