Spring的代码入口ContextLoaderListener

1.监听器

public class ContextLoaderListener extends ContextLoader implements ServletContextListener

ContextLoaderListener 是spring-web中的类,实现了servlet-api中的接口ServletContextListener ,继承了
spring-web中ContextLoader

该类重要是实现接口中的contextInitialized方法,该类主要是监听ServletContext(应用上下文)的创建和销毁,当创建时初始化Spring容器,而实际的执行方法initWebApplicationContext是定义在父类ContextLoader,创建一个web容器类.

2.Spring容器的存放

servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

把生成的Spring容器存放到servletCotext上下文中,key是WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE

所以引申出是否已经存在spring容器的判断

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!");
		}

知道了spring容器的位置,我们就可以获取到spring容器,从而获取到被容器管理的bean.

3.Spring容器的创建

ContextLoader 类中的createWebApplicationContext用来创建容器,是通过反射来创建

//这段代码是在ContextLoader.initWebApplicationContext方法中
if (this.context == null) {
				this.context = createWebApplicationContext(servletContext);
			}

但是容器的实现类有很多,所以需要判断到底用哪一个实现类
所以在createWebApplicationContext方法中出现这段代码

//该方法用来确定到底使用哪一个实现类
Class<?> contextClass = determineContextClass(sc);
  1. 实现类的字符串可以定义在web.xmlcontext-param的标签中.
  2. 定义在ContextLoader.properties文件中,这是一个默认的配置文件.

ContextLoader.properties 的位置,在jar包中

org/springframework\web\context\ContextLoader.properties

ContextLoader.properties 的内容

org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext

4.返回容器

判断ConfigurableWebApplicationContext是否是XmlWebApplicationContext的父类,返回容器

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);		
发布了66 篇原创文章 · 获赞 8 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq125281823/article/details/105127918
今日推荐