为何实现ServletContextAware接口就可以获得servletContext

为何实现ServletContextAware接口就可以获得servletContext

今天看某个项目,发现他实现了ServletContextAware接口,然后就可以直接获得了servletContext

最后简单的查看了下源码,发现他的运行方式时这样的

首先时springmvc容器启动时

他会对XmlWebApplicationContext的实例化及对其属性的设置

XmlWebApplicationContext,其中的部分不代码如下

public class XmlWebApplicationContext extends AbstractRefreshableWebApplicationContext {

	/** Default config location for the root context */
	public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";

	/** Default prefix for building a config location for a namespace */
	public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";

	/** Default suffix for building a config location for a namespace */
	public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml";
这些信息是不是很熟悉,是不是我们更加认为springmvc启动时就会加载他。


当然他还继承了AbstractRefreshableWebApplicationContext这个抽象类

在这个抽象类里面他实现了很多接口,其中也实现了 ConfigurableWebApplicationContext这个接口

ConfigurableWebApplicationContext这个接口他又继承了很多接口,这里为就不写了

总之在这很多的接口之中,有一个继承了ServletContextAware接口


所以我们主要看看AbstractRefreshableWebApplicationContext这个抽象类中的方法

public abstract class AbstractRefreshableWebApplicationContext extends AbstractRefreshableConfigApplicationContext
		implements ConfigurableWebApplicationContext, ThemeSource {

	/** Servlet context that this context runs in */
	private ServletContext servletContext;

	/** Servlet config that this context runs in, if any */
	private ServletConfig servletConfig;

	/** Namespace of this context, or {@code null} if root */
	private String namespace;

	/** the ThemeSource for this ApplicationContext */
	private ThemeSource themeSource;


	public AbstractRefreshableWebApplicationContext() {
		setDisplayName("Root WebApplicationContext");
	}


	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
这个抽象类中有被实现的方法  setServletContext方法,这个方法就获得了ServletContext


我们只需要ServletContextAware,就可以获得ServletContext上下文


爆款云服务器s6 2核4G 低至0.46/天,具体规则查看活动详情Blog Img