Spring IOC容器如何與web容器創建聯繫,使得在web環境下能運用Spring 容器去管理對象,這要從web.xml配置文件中的ContextLoaderListener提及。它是Spring容器與web容器創建聯繫的入口,這裏就先拋磚引玉啦。web
先來看看web.xml配置文件中的spring
<context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring/spring-context.xml, classpath:spring/spring-datasource.xml, classpath:spring/spring-context-shiro.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
這個你們一字很熟悉,這即是Spring容器與web容器創建聯繫的入口。來看看ContextLoaderListener的源碼app
public class ContextLoaderListener extends ContextLoader implements ServletContextListener { public ContextLoaderListener() { } public ContextLoaderListener(WebApplicationContext context) { super(context); } @Override public void contextInitialized(ServletContextEvent event) { initWebApplicationContext(event.getServletContext()); } @Override public void contextDestroyed(ServletContextEvent event) { closeWebApplicationContext(event.getServletContext()); ContextCleanupListener.cleanupAttributes(event.getServletContext()); } }
能夠看到其實現了ServletContextListener 接口,這樣即可以從web.xml文件中加載ServletContext一些配置信息,兼聽ServletContext上下文的變化狀況。ServletContextListener 有兩個方法contextInitialized 與contextDestroyed,contextInitialized 在容器啓動時調用,contextDestroyed在容器關閉前調用。 能夠看到在ContextLoaderListener中 contextInitialized 內部調用了父類ContextLoader 的initWebApplicationContext方法,這即是Spring容器初始化的入口。ide
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { //判斷是否已初始化過Spring容器,若是有拋出異常 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) { //建立Spring容器,默認狀況下爲XmlWebApplicationContext 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); } //配置Spring容器,加載servletContext的一些配置文件 configureAndRefreshWebApplicationContext(cwac, servletContext); } } //將WebApplicationContext對象保存在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; }
這裏忽視一些細節,重點看看initWebApplicationContext方法中this
createWebApplicationContext //建立Spring容器,默認狀況下爲XmlWebApplicationContext this.context = createWebApplicationContext(servletContext) context是ContextLoader的成員變量,其類型爲WebApplicationContext,WebApplicationContext續承ApplicationContext爲Spring的容器。 再來看看源碼spa
protected WebApplicationContext createWebApplicationContext(ServletContext sc) { //採用什麼類型的FactoryBean建立Spring 容器 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源碼debug
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); } } }
默認狀況下在web.xml中不會設置SevletContext的contextClass參數,便根據defaultStrategies.getProperty(WebApplicationContext.class.getName())查找Spring容器對應的實現類。 defaultStrategies爲ContextLoader的類型爲Properties的靜態成員變量,ContextLoader內有一個靜態初始化塊對其進行初始化。code
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()); } }
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class)
這一行代碼能夠看出,初始化塊將找DEFAULT_STRATEGIES_PATH這個路徑的文件,其實是ClassPathResource將到ContextLoader包對應的路徑下面找到ContextLoader.properties文件。 xml
再打ContextLoader.properties看看其內容: 對象
能夠看到前面說的Spring容器的默認實現類XmlWebApplicationContext,最後這個經過反射createWebApplicationContext將返回XmlWebApplicationContext的對象給ContextLoader的成員變量context。 到這裏**1. this.context = createWebApplicationContext(servletContext);**分析結束。
再來看看**2. configureAndRefreshWebApplicationContext(cwac, servletContext);**的分析 configureAndRefreshWebApplicationContext源碼:
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) { if (ObjectUtils.identityToString(wac).equals(wac.getId())) { 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); //獲得web.xml中ServletContext參數contextConfigLocation對應的配置信息 String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM); if (configLocationParam != null) { //將配置信息進行解析並設置 wac.setConfigLocation(configLocationParam); } ConfigurableEnvironment env = wac.getEnvironment(); if (env instanceof ConfigurableWebEnvironment) { ((ConfigurableWebEnvironment) env).initPropertySources(sc, null); } customizeContext(sc, wac); //Spring容器真正初始化的地方 wac.refresh(); }
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
這行代碼將獲得在web.xml中的Spring配置文件的信息,就是一開始 的web.xml的這部分
<context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring/spring-context.xml, classpath:spring/spring-datasource.xml, classpath:spring/spring-context-shiro.xml </param-value> </context-param>
再來分析一下**wac.setConfigLocation(configLocationParam)**這行代碼 從上面的分析知道默認狀況下wac爲XmlWebApplicationContext類型的對象。 在XmlWebApplicationContext的父類AbstractRefreshableWebApplicationContext實現了ConfigurableWebApplicationContext接口,而另外一方面AbstractRefreshableWebApplicationContext又續承了AbstractRefreshableConfigApplicationContext類。AbstractRefreshableConfigApplicationContext類裏面實現了setConfigLocation方法。
public void setConfigLocation(String location) { setConfigLocations(StringUtils.tokenizeToStringArray(location, CONFIG_LOCATION_DELIMITERS)); }
String CONFIG_LOCATION_DELIMITERS = ",; \t\n"; 從這裏能夠看出,在web.xml裏面設置contextConfigLocation的param-value時,能夠用",; \t\n"來分隔多個配置文件。
public void setConfigLocations(String... locations) { if (locations != null) { Assert.noNullElements(locations, "Config locations must not be null"); this.configLocations = new String[locations.length]; for (int i = 0; i < locations.length; i++) { this.configLocations[i] = resolvePath(locations[i]).trim(); } } else { this.configLocations = null; } }
再回到configureAndRefreshWebApplicationContext方法中wac.refresh()這一行,這纔是Spring容器真正初始化的地方,因爲後面涉及的東西比較多將在後面專門分析一下。 到這裏2. configureAndRefreshWebApplicationContext(cwac, servletContext);的分析結束。 再來看看3.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); 這個比較簡單就是將上面用反射方法建立的XmlWebApplicationContext對象保存在ServletContext上下文中。因爲本人水平有限不正確的地方,歡迎你們指正。