spring源码分析之IOC开篇
2018-01-28 22:58
357 查看
SpringMVC的核心就是IOC与AOP。此篇将作为IOC的开篇
在web.xml中有这样一段配置
ContextLoaderListener实现了ServletContextListener接口。而ServletContextListener作为java EE的标准接口之一。所以当tomcat,was等容器启动的时候就会触发监听类ContextLoaderListener的contextInitialized()
然后进入ContextLoader类中的initWebApplicationContext()
如果上图看不清楚,可以看下面的源码。
图中关键的方法用红色框选中
3、然后就进入AbstractApplicationContext的具体实现方法refresh()中。这个方法是整个IOC的核心方法,接下来将会以这个方法里面涉及到的方法展开分析。
开篇就到这里,接下来会对refresh 方法逐一展开。
在web.xml中有这样一段配置
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
ContextLoaderListener实现了ServletContextListener接口。而ServletContextListener作为java EE的标准接口之一。所以当tomcat,was等容器启动的时候就会触发监听类ContextLoaderListener的contextInitialized()
/** * Initialize the root web application context. */ @Override public void contextInitialized(ServletContextEvent event) { initWebApplicationContext(event.getServletContext()); }
然后进入ContextLoader类中的initWebApplicationContext()
如果上图看不清楚,可以看下面的源码。
/** * Initialize Spring's web application context for the given servlet context, * using the application context provided at construction time, or creating a new one * according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and * "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params. * @param servletContext current servlet context * @return the new WebApplicationContext * @see #ContextLoader(WebApplicationContext) * @see #CONTEXT_CLASS_PARAM * @see #CONFIG_LOCATION_PARAM */ 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); } if (this.context instanceof ConfigurableWebApplicationContext) { configureAndRefreshWebApplicationContext((ConfigurableWebApplicationContext)this.context, 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; } }
图中关键的方法用红色框选中
3、然后就进入AbstractApplicationContext的具体实现方法refresh()中。这个方法是整个IOC的核心方法,接下来将会以这个方法里面涉及到的方法展开分析。
@Override public void refresh() throws BeansException, 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) { 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(); } } }
开篇就到这里,接下来会对refresh 方法逐一展开。
相关文章推荐
- Spring源码分析IOC实现一BeanFactory
- Spring IOC源码分析
- spring源码分析,重新认识spring三(总结,总结下 ioc 和 aop,同时提出疑惑)
- (十)Spring事务处理 - IoC容器的事务处理源码分析
- Spring IOC 容器源码分析 - 获取单例 bean
- Spring IOC学习心得之源码级分析ContextLoaderListener的作用(IOC容器初始化入口)
- 做一个合格的程序猿之浅析Spring IoC源码(一)分析前的准备和思考
- Spring原理与源码分析系列(四)- Spring IoC源码分析(上)
- Spring源码分析(二)-Spring IoC容器的初始化No.1
- spring ioc 源码分析 1
- Spring源码分析----IoC容器(一)
- 深入研究Spring-IoC:源码分析容器创建
- Spring IOC 容器源码分析 - 余下的初始化工作
- spring源码学习之路---深度分析IOC容器初始化过程(三)
- 一 spring源码分析--- IOC容器
- spring4.2.9 ioc源码分析(一)——执行refresh之前
- Spring源码分析--Ioc容器定位解析资源文件并注册BeanDefinition
- Spring源码学习IOC(1):Resource的分析
- spring源码分析之IOC(三)
- Spring IOC 容器源码分析 - 创建原始 bean 对象