web.xml文件中配置了ContextLoaderListener监视器,在Web项目启动的时候由Tomcat创建ContextLoaderListener的实例。
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
2.2.1、ServletContextListener
监听Web应用的ServletContext对象生命周期的变化,由于ServletContext对象的生命周期因Web应用的启动停止而变化,实际上也就是监听了Web应用的启动和停止,当启动和终止Web应用时,会触发ServletContextEvent事件,该事件由ServletContextListener来处理。
package javax.servlet;
import java.util.EventListener;
public interface ServletContextListener extends EventListener {
/**
* Web应用启动时
* 调用该方法后,容器再初始化filter/servlet(设置为启动时加载的servlet)
*
* @param sce the ServletContextEvent containing the ServletContext
* that is being initialized
*/
public void contextInitialized(ServletContextEvent sce);
/**
* Web应用终止时
* 调用该方法前,容器会先销毁servlet/filter
*/
public void contextDestroyed(ServletContextEvent sce);
}
2.2.2、ContextLoaderListener的加载/创建/初始化
2.2.2.1、ContextLoaderListener类加载
1、加载ContextLoaderListener
2、加载ContextLoader
// 代码片段,注释一些较为关键的地方(后续需要用到的信息)
public class ContextLoader {
public static final String CONTEXT_ID_PARAM = "contextId";
public static final String CONFIG_LOCATION_PARAM = "contextConfigLocation";
// ServletContext中是否存储了key为contextClass的key-value,这个value将作为根WebApplocationContext的实现类
// 一般配置方式:web.xml文件中,以<context-param>标签设置
public static final String CONTEXT_CLASS_PARAM = "contextClass";
public static final String CONTEXT_INITIALIZER_CLASSES_PARAM = "contextInitializerClasses";
public static final String GLOBAL_INITIALIZER_CLASSES_PARAM = "globalInitializerClasses";
private static final String INIT_PARAM_DELIMITERS = ",; \t\n";
// 默认的保存策略文件路径
private static final String DEFAULT_STRATEGIES_PATH = "ContextLoader.properties";
// 保存策略文件中的信息:key-value
private static final Properties defaultStrategies;
static {
// 读取策略文件DEFAULT_STRATEGIES_PATH存入defaultStategies中,策略文件中包含的内容:
// org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
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());
}
}
private static final Map<ClassLoader, WebApplicationContext> currentContextPerThread =
new ConcurrentHashMap<>(1);
@Nullable
private static volatile WebApplicationContext currentContext;
@Nullable
private WebApplicationContext context;
......
}
2.2.2.2、ContextLoaderListener类创建&初始化
1、创建过程调用无参构造器,本类及其父类
public ContextLoaderListener() {}
public ContextLoader() {}
2.2.3、ContextLoaderListener监听到Web项目启动
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
// 防止为一个Web项目创建多个根IOC容器
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 {
// 存储与ContextLoaderListener对象的实例字段,以便在Web停止时调用context.close()方法
if (this.context == null) {
this.context = createWebApplicationContext(servletContext);
}
// 创建WebApplicationContext的对象正常来说,判断为true
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
if (!cwac.isActive()) {
if (cwac.getParent() == null) { //设置父WebApplicationContext,由于ContextLoaderListener创建的就是最顶层ApplicationContext,这里直接返回null
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); // 将完成初始化&refresh的根WebApplicationContext放入ServletContext中
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;
}
catch (RuntimeException ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
catch (Error err) {
logger.error("Context initialization failed", err);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
throw err;
}
}
1、创建WebApplicationContext对象
// ContextLoader
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
// 判断使用哪个WebApplicationContext
Class<?> contextClass = determineContextClass(sc);
// 判断ConfigurableWebApplicationContext.class与contextClass表示相同的类/接口,是否是contextClass的超类/超接口,是返回True
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
}
// 反射,使用contextClass的无参构造器创建,见“反射创建对象的过程”,WebApplicationContext创建过程(其及其父类的构造函数执行的操作)
return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}
// ContextLoader
protected Class<?> determineContextClass(ServletContext servletContext) {
// servletContext中是否有指定要使用的ApplicationContext实现类
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 {
// 未指定,使用策略文件中默认的:org.springframework.web.context.WebApplicationContext为key
contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
try {
// 类加载器加载类类,返回该类的Class对象实例
return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load default context class [" + contextClassName + "]", ex);
}
}
}
反射创建对象的过程
// org.springframework.beans.BeanUtils
public static <T> T instantiateClass(Class<T> clazz) throws BeanInstantiationException {
Assert.notNull(clazz, "Class must not be null");
if (clazz.isInterface()) { // 如果clazz代表接口,抛异常
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
// 反射获取实例clazz的实例无参构造器
// KotlinDetector.isKotlinType(clazz)不知道有何作用,但是单步调试这个结果是false,故使用clazz.getDeclaredConstructor()获得构造器
Constructor<T> ctor = (KotlinDetector.isKotlinType(clazz) ?
KotlinDelegate.getPrimaryConstructor(clazz) : clazz.getDeclaredConstructor());
return instantiateClass(ctor);
}
catch (NoSuchMethodException ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
catch (LinkageError err) {
throw new BeanInstantiationException(clazz, "Unresolvable class definition", err);
}
}
public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
Assert.notNull(ctor, "Constructor must not be null");
try {
ReflectionUtils.makeAccessible(ctor); // 针对非public的构造器设置访问属性,确保构造器可被调用
// Constructor.newInstance()反射创建对象
return (KotlinDetector.isKotlinType(ctor.getDeclaringClass()) ?
KotlinDelegate.instantiateClass(ctor, args) : ctor.newInstance(args));
}
catch (InstantiationException ex) {
throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex);
}
catch (IllegalAccessException ex) {
throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex);
}
catch (IllegalArgumentException ex) {
throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex);
}
catch (InvocationTargetException ex) {
throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException());
}
}
// org.springframework.util.ReflectionUtils
@SuppressWarnings("deprecation") // on JDK 9
public static void makeAccessible(Constructor<?> ctor) {
if ((!Modifier.isPublic(ctor.getModifiers()) ||
!Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) && !ctor.isAccessible()) {
ctor.setAccessible(true);
}
}
WebApplicationContext类
a.XmlWebApplicationContext及其父类加载
b.XmlWebApplicationContext及其父类创建&初始化
// XmlWebApplicationContext,无参构造函数为默认的构造函数
public AbstractRefreshableWebApplicationContext() {
setDisplayName("Root WebApplicationContext");
}
public AbstractRefreshableConfigApplicationContext() {}
public AbstractRefreshableApplicationContext() {}
public AbstractApplicationContext() {
this.resourcePatternResolver = getResourcePatternResolver();
}
protected ResourcePatternResolver getResourcePatternResolver() {
return new PathMatchingResourcePatternResolver(this);
}
public void setDisplayName(String displayName) {
Assert.hasLength(displayName, "Display name must not be empty");
this.displayName = displayName;
}
private String id = ObjectUtils.identityToString(this);
public DefaultResourceLoader() {
this.classLoader = ClassUtils.getDefaultClassLoader();
}
2、配置&Refreah新创建的WebApplicationContext对象
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) { // ServletContext中指定了CONTEXT_ID_PARAM,则设置为指定的
wac.setId(idParam);
}
else {
// 否则设置为:WebApplicationContext.class.getName() + ":" + ...
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); //web.xml中<context-param>的name为contextConfigLocation的配置文件,Spring的配置文件
}
// 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);
// XmlWebApplicationContext的refresh()函数
wac.refresh();
}
// AbstractApplicationContext
// XmlWebApplicationContext的继承关系,找到AbstractApplicationContext的refresh函数
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) { //同步,避免重复刷新
// Prepare this context for refreshing.
prepareRefresh();
// 解析xml文件,找出需要创建的Bean的BeanDefinition,存入beanFactory的BeanDefinitionMap和BeanDefinitionNames中
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// 创建beanFactory中待创建的Bean(单例,非懒汉)
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
如有不当之处,欢迎指正不胜感激