开发者

Spring中的ContextLoaderListener详细解析

开发者 https://www.devze.com 2023-12-09 10:23 出处:网络 作者: 遇见更好的自己、
目录前言ContextLoaderListener的实现Spring容器初始化总结前言 我们已经了解到,在web容器即ToMACt容器启动web应用即servlet应用时,会触发ServletContextEvent时间,这个事件会被ServletContextListener监听,监听
目录
  • 前言
  • ContextLoaderListener的实现
  • Spring容器初始化
  • 总结

前言

我们已经了解到,在web容器即ToMACt容器启动web应用即servlet应用时,会触发ServletContextEvent时间,这个事件会被ServletContextListener监听,监听到了以后会通过ContextLoaderListener监听器(ServletContextListener的一个实现类)去初始化Spring容器其实就是去初始化一些Bean。即默认WEB-INF/applicationContext.XML文件的配置信息。

关于有如下两点需要理解:

1.web项目自身:接收web容器启动web应用的通知,开始自身配置的解析加载,创建bean实例,通过一个WebApplicationContext来维护spring项目的主容器相关的bean,以及其他一些组件。

2.web容器:web容器使用ServletContext来维护每一个web应用,ContextLoaderListener将sprhttp://www.devze.coming容器,即WebApplicationContext,作为ServletContext的一个attribute,key为WebApplicationContext.class.getName() + “.ROOT”,保存在ServletContext中,从而web容器和spring项目可以通过ServletContext来交互。

ContextLoaderListener只是作为一个中间层来建立spring容器和web容器的关联关系,而实际完成以上两个角度的工作是通过ContextLoader来进行的,即在ContextLoader中定义以上逻辑,

ContextLoaderListener的实现

ContextLoaderListener的源码如下:

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
	/**
	 * Create a new {@code ContextLoaderListener} that will create a web application
	 * context based on the "contextClass" and "contextConfigLocation" servlet
	 * context-params. See {@link ContextLoader} superclass documentation for details on
	 * default values for each.
	 * <p>This constructor is typically used when declaring {@code ContextLoaderListener}
	 * as a {@code <listener>} within {@code web.xml}, where a no-arg constructor is
	 * required.
	 * <p>The created application context will be registered intphpo the ServletContext under
	 * the attribute name {@link WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE}
	 * and the Spring application context will be closed when the {@link #contextDestroyed}
	 * lifecycle method is invoked on this listener.
	 * @see ContextLoader
	 * @see #ContextLoaderListener(WebApplicationContext)
	 * @see #contextInitialized(ServletContextEvent)
	 * @see #contextDestroyed(ServletContextEvent)
	 */
	public ContextLoaderListener() {
	}
	/**
	 * Create a new {@code ContextLoaderListener} with the given application context. This
	 * constructor is useful in Servlet 3.0+ environments where instance-based
	 * registration of listeners is possible through the {@link Javax.servlet.ServletContext#addListener}
	 * API.
	 * <p>The context may or may not yet be {@linkplain
	 * org.springframework.context.ConfigurableApplicationContext#refresh() refreshed}. If it
	 * (a) is an implementation of {@link ConfigurableWebApplicationContext} and
	 * (b) has <strong>not</strong> already been refreshed (the recommended approach),
	 * then the following will occur:
	 * <ul>
	 * <li>If the given context has not already been assigned an {@linkplain
	 * org.springframework.context.ConfigurableApplicationContext#setId id}, one will be assigned to it</li>
	 * <li>{@code ServletContext} and {@code ServletConfig} objects will be delegated to
	 * the application context</li>
	 * <li>{@link #customizeContext} will be called</li>
	 * <li>Any {@link org.springframework.context.ApplicationContextInitializer ApplicationContextInitializer org.springframework.context.ApplicationContextInitializer ApplicationContextInitializers}
	 * specified through the "contextInitializerClasses" init-param will be applied.</li>
	 * <li>{@link org.springframework.context.ConfigurabljseApplicationContext#refresh refresh()} will be called</li>
	 * </ul>
	 * If the context has already been refreshed or does not implement
	 * {@code ConfigurableWebApplicationContext}, none of the above will occur under the
	 * assumption that the user has performed these actions (or not) per his or her
	 * specific needs.
	 * <p>See {@link org.springframework.web.WebApplicationInitializer} for usage examples.
	 * <p>In any case, the given application context will be registered into the
	 * ServletContext under the attribute name {@link
	 * WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE} and the Spring
	 * application context will be closed when the {@link #contextDestroyed} lifecycle
	 * method is invoked on this listener.
	 * @param context the application context to manage
	 * @see #contextInitialized(ServletContextEvent)
	 * @see #contextDestroyed(ServletContextEvent)
	 */
	public ContextLoaderListener(WebApplicationContext context) {
		super(context);
	}
	/**
	 * Initialize the root web application context.
	 */
	@Override
	public void contextInitializedpython(ServletContextEvent event) {
		initWebApplicationContext(event.getServletContext());
	}
	/**
	 * Close the root web application context.
	 */
	@Override
	public void contextDestroyed(ServletContextEvent event) {
		closeWebApplicationContext(event.getServletContext());
		ContextCleanupListener.cleanupAttributes(event.getServletContext());
	}

可以看到ContextLoaderListener继承了ServletContextListener并实现了ContextLoader类。

在web容器启动的时候,ContextLoaderListener就会监听到。

并将监听事件传入到方法:contextInitialized(ServletContextEvent event)中,然后,调用了父类的方法去初始化initWebApplicationContext:

Spring容器初始化

接下来我们的重点是Spring容器是如何初始化的:

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) {
              // 创建一个WebApplicationContext
                   // 具体类型如果是指定了contextClass则使用该指定的;
               // 默认使用XmlWebApplicationContext
				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);
					}
                          // 核心方法,完成配置加载,BeanDefinition定义和bean对象创建
					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;
		}
	}

在看上述代码前,我们需要了解ContextLoader的一些重要含义

ContextLoader主要负责加载spring主容器,即root ApplicationContext,在设计层面主要定义了contextId,contextConfigLocation,contextClass,contextInitializerClasses。这些参数都可以在配置中指定,如web.xml的context-param标签,或者是基于Java编程方式配置的WebApplicationInitializer中定义,作为分别为:contextId:当前容器的id,主要给底层所使用的BeanFactory,在进行序列化时使用。

  • contextConfigLocation:配置文件的位置,默认为WEB-INF/applicationContext.xml,可以通过在web.xml使用context-param标签来指定其他位置,其他名字或者用逗号分隔指定多个。在配置文件中通过beans作为主标签来定义bean。这样底层的BeanFactory会解析beans标签以及里面的bean,从而来创建BeanDefinitions集合,即bean的元数据内存数据库。
  • contextClass:当前所使用的WebApplicationContext的类型,如果是在WEB-INF/applicationContext.xml中指定beans,则使用XmlWebApplicationContext,如果是通过注解,如@Configuration,@Component等,则是AnnotationConfigWebApplicationContext,通过扫描basePackages指定的包来创建bean。
  • contextInitializerClasses:ApplicationContextInitializer的实现类,即在调用ApplicationContext的refresh加载beanDefinition和创建bean之前,对WebApplicationContext进行一些初始化

configureAndRefreshWebApplicationContext源码如下:

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);
		// ApplicationContext的核心方法:在refresh方法中完成ApplicationContext的启动
		// 即spring容器的各个核心组件的创建,如beanDefinitions,enviromnet等
		wac.refresh();
	}

总结

通过上面的分析可知,ContextLoader完成spring主容器的创建,工作主要是负责从ServletContext中,具体为ServletContext从web.xml文件或者WebApplicationInitializer的实现类中,获取WebApplicationContext的相关配置信息,如使用contextClass指定使用哪种WebApplicationContext实现,contextConfigLocation指定spring容器的配置文件在哪里,以及获取WebApplicationContextInitializers来在进行spring容器创建之前,对WebApplicationContext进行加工处理。

而spring容器的创建,则是使用spring-context包的ApplicationContext,spring-beans包的BeanFactory,来完成从配置中获取beans定义并创建BeanDefinition,获取一些资源属性值,以及完成单例bean的创建等。具体在之后关于ApplicationContext和BeanFactory体系结构的文章中分析。

到此这篇关于Spring中的ContextLoaderListener详细解析的文章就介绍到这了,更多相关Spring中的ContextLoaderListener内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号