Spring的初始化:org.springframework.web.context.ContextLoaderListener
在web.xml中配置
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
ContextLoaderListener的作用就是啟動Web容器時,自動裝配ApplicationContext.xml的配置信息。因為它實現了ServletContextListener這個接口,在web.xml配置這個監聽器,啟動容器時,就會默認執行它實現的方法。
ApplicationContext.xml這個配置文件部一般默認放置在。applicationContext的默認的路徑是”/WEB-INF/applicationContext.xml。也可以在web.xml中配置該文件的其他位置,配置如下:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
classpath:applicationContext-security.xml;
</param-value>
</context-param>
以下詳解
org.springframework.web.context.ContextLoaderListener類實現了javax.servlet.ServletContextListener接口。ServletContextListener接口能夠監聽ServletContext對象的生命周期,因為每個web應用僅有一個ServletContext對象,故實際上該接口監聽的是整個web應用。
實現該接口的類在web.xml中作為監聽器配置后,當web應用啟動后,會觸發ServletContextEvent事件,調用ContextLoaderListener的contextInitialized(ServletContextEvent sce)方法。
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對象。
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。