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上下文中。因为本人水平有限不正确的地方,欢迎你们指正。