SpringMVC源码-ContextLoaderListener
ContextLoaderListener是web容器与Spring上下文整合的监听器。在web.xml中配置
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
当容器启动后,ServletContextListener会执行contextInitialized方法。ContextLoaderListener实现了ServletContextListener接口。
ContextLoaderListener.contextInitialized(ServletContextEvent event)
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
ContextLoaderListener.initWebApplicationContext(ServletContext servletContext)
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!");
}
servletContext.log("Initializing Spring root WebApplicationContext");
Log logger = LogFactory.getLog(ContextLoader.class);
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) {
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);
}
configureAndRefreshWebApplicationContext(cwac, 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.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("Root WebApplicationContext initialized in " + elapsedTime + " ms");
}
return this.context;
}
catch (RuntimeException | Error ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
}
1、createWebApplicationContext创建Spring Context上下文
2、判断context是否是ConfigurableWebApplicationContext,如果是且未活动,context的父容器为空则调用loadParentContext加载父上下文。调用configureAndRefreshWebApplicationContext配置和刷新上下文。
3、在servletContext设置属性名为WebApplicationContext.class.getName() + ".ROOT",值为WebApplicationContext的属性
ContextLoader.createWebApplicationContext(ServletContext sc)
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
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);
}
1、determineContextClass决定WebApplicationContext的类型,Class是XmlWebApplicationContext。
2、调用BeanUtils.instantiateClass实例化
ContextLoader.determineContextClass(ServletContext servletContext)
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);
}
}
}
1、从ServletContext获取contextClass初始化参数,如果不为空调用ClassUtils.forName获取Class。
2、否则从defaultStrategies中获取属性名为WebApplicationContext.class.getName()的属性值,调用ClassUtils.forName获取Class。
ContextLoader.defaultStrategies
private static final String DEFAULT_STRATEGIES_PATH = "ContextLoader.properties";
private static final Properties defaultStrategies;
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());
}
}
加载web项目下的classpath目录resources/org/springframework/web/context/ContextLoader.properties属性文件。
ContextLoader.properties
# Default WebApplicationContext implementation class for ContextLoader.
# Used as fallback when no explicit context implementation has been specified as context-param.
# Not meant to be customized by application developers.
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
ContextLoader.loadParentContext(ServletContext servletContext)
protected ApplicationContext loadParentContext(ServletContext servletContext) {
return null;
}
ContextLoader.configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc)
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
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);
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}
// The wac environment's #initPropertySources will be called in any case when the context
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}
customizeContext(sc, wac);
wac.refresh();
}
1、ConfigurableWebApplicationContext设置id
2、ConfigurableWebApplicationContext设置ServletContext
3、从ServletContext获取contextConfigLocation参数并设置到ConfigurableWebApplicationContext,即web.xml文件中配置的参数:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:app-mvc.xml</param-value>
</context-param>
4、获取Environment,调用initPropertySources替换servletContextInitParams和servletConfigInitParams属性值
5、customizeContext自定义context
6、刷新容器,即调用AbstractApplicationContext.refresh()刷新容器,加载并解析xml文件成BeanDifinition,创建bean。
ContextLoader.customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac)
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses =
determineContextInitializerClasses(sc);
for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) {
Class<?> initializerContextClass =
GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) {
throw new ApplicationContextException(String.format(
"Could not apply context initializer [%s] since its generic parameter [%s] " +
"is not assignable from the type of application context used by this " +
"context loader: [%s]", initializerClass.getName(), initializerContextClass.getName(),
wac.getClass().getName()));
}
this.contextInitializers.add(BeanUtils.instantiateClass(initializerClass));
}
AnnotationAwareOrderComparator.sort(this.contextInitializers);
for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : this.contextInitializers) {
initializer.initialize(wac);
}
}
1、determineContextInitializerClasses从ServletContext获取globalInitializerClasses和contextInitializerClasses参数解析成ApplicationContextInitializer组成initializerClasses List。ApplicationContextInitializer是ConfigurableApplicationContext#refresh刷新之前初始化ConfigurableApplicationContext的回调接口。
2、遍历initializerClasses集合,实例化每个对象后加入contextInitializers集合
3、按照Order接口排序contextInitializers集合
4、遍历contextInitializers集合调用每个ApplicationContextInitializer的initialize方法。
总结:
ContextLoaderListener监听容器启动后出发的上下文初始化事件并执行contextInitialized方法,从web.xml文件中解析参数为contextConfigLocation的spring的配置文件,实例化类型是XmlWebApplicationContext的Spring Context对象。并解析加载Spring的配置文件,生成BeanDifinition,进行创建bean。ContextLoaderListener主要作用是生成了Spring的上下文,创建了Spring上下文的bean。