Spring启动过程追踪
闲来无事,想着把spring工作机制梳理梳理,当下spring框架确实是非常牛逼的存在,扩展了很多模块,springboot springcloud springsecurity等都是spring衍生出来的
web容器启动
WEB项目启动时候,会加载web.xml文件,在web.xml中配置了ContextLoaderListener(监听器),下面分析下这个监听器对象
1、ContextLoaderListener类信息
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
..
/**
* 初始化web上下文环境
*/
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
/**
* 关闭web容器
*/
@Override
public void contextDestroyed(ServletContextEvent event) {
closeWebApplicationContext(event.getServletContext());
ContextCleanupListener.cleanupAttributes(event.getServletContext());
}
}
2、initWebApplicationContext(event.getServletContext());初始化方法
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!");
}
......
if (this.context == null) {
//创建web环境
this.context = createWebApplicationContext(servletContext);
}
.......
//配置spring配置文件
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}
//刷新容器
configureAndRefreshWebApplicationContext(cwac, servletContext);
return this.context;
}
}
3、createWebApplicationContext(servletContext);
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
Class<?> contextClass = determineContextClass(sc);
...
return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}
4、determineContextClass(sc);
注意:defaultStrategies是配置文件资源信息,见下图
contextLoader.properties配置文件在spring-web的jar包中的位置如下图
我们稍微看一眼这个配置文件中是啥哈
默认是XmlWebApplicationContext
至此,XmlWebApplicationContext被创建对象完成,回到 2步骤中的initWebApplicationContext方法,可以看到,会进行容器刷新操作
configureAndRefreshWebApplicationContext(cwac, servletContext);
进入方法会发现 wac.refresh();被调用,即XmlWebApplicationContext的refresh方法触发
总结:本文简单说明了spring默认xml配置方法的上下文环境启动的前奏,当然现在大多数是注解形式的,这个在代码中有所表示,我们可以配置在web.xml中,初始化参数配置中添加contextClass 节点 为AnnotationConfigApplicationContext即可