在web.xml中配置java
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>web
ContextLoaderListener的做用就是启动Web容器时,自动装配ApplicationContext.xml的配置信息。由于它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。
ApplicationContext.xml这个配置文件部通常默认放置在。applicationContext的默认的路径是”/WEB-INF/applicationContext.xml。也能够在web.xml中配置该文件的其余位置,配置以下:spring
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
classpath:applicationContext-security.xml;
</param-value>
</context-param>app
如下详解spa
org.springframework.web.context.ContextLoaderListener类实现了javax.servlet.ServletContextListener接口。ServletContextListener接口可以监听ServletContext对象的生命周期,由于每一个web应用仅有一个ServletContext对象,故实际上该接口监听的是整个web应用。code
实现该接口的类在web.xml中做为监听器配置后,当web应用启动后,会触发ServletContextEvent事件,调用ContextLoaderListener的contextInitialized(ServletContextEvent sce)方法。xml
ContextLoaderListener经过一个ContextLoader对象来初始化Spring容器。在contextInitialized方法中调用contextLoader.initWebApplicationContext(event.getServletContext())。对象
ContextLoader类的initWebApplicationContext方法便可返回一个WebApplicationContext对象context。并经过 servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context)将WebApplicationContext对象放置在ServletContext对象中。initWebApplicationContext方法经过调用如下方法实例化并设置WebApplicationContext对象。blog
protected WebApplicationContext createWebApplicationContext(ServletContext servletContext, ApplicationContext parent) throws BeansException { Class contextClass = determineContextClass(servletContext);//经过servletContext肯定WebApplicationContext的具体类型 if(!(org.springframework.web.context.ConfigurableWebApplicationContext.class).isAssignableFrom(contextClass)) { throw new ApplicationContextException("Custom context class [" + contextClass.getName() + "] is not of type [" + (org.springframework.web.context.ConfigurableWebApplicationContext.class).getName() + "]"); } else { ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext)BeanUtils.instantiateClass(contextClass); wac.setParent(parent); wac.setServletContext(servletContext); wac.setConfigLocation(servletContext.getInitParameter("contextConfigLocation"));//设置配置文件的路径名 customizeContext(servletContext, wac); wac.refresh(); return wac; } }
所以能够经过WebApplicationContextUtils.getWebApplicationContext(ServletContext sc)获取WebApplicationContext。内部实现是经过servletContext对象查找该对象,属性名为WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE。接口