spring上下文

应用上下文即是Spring容器抽象的一种实现;而我们常见的ApplicationContext本质上说就是一个维护Bean定义以及对象之间协作关系的高级接口。额,听起来是不是很抽象拗口?那你再读一遍呢。。。这里,我们必须明确,Spring的核心是容器,而容器并不唯一,框架本身就提供了很多个容器的实现,大概分为两种类型:一种是不常用的BeanFactory,这是最简单的容器,只能提供基本的DI功能;还有一种就是继承了BeanFactory后派生而来的应用上下文,其抽象接口也就是我们上面提到的的ApplicationContext,它能提供更多企业级的服务,例如解析配置文本信息等等,这也是应用上下文实例对象最常见的应用场景。有了上下文对象,我们就能向容器注册需要Spring管理的对象了。对于上下文抽象接口,Spring也为我们提供了多种类型的容器实现,供我们在不同的应用场景选择——

① AnnotationConfigApplicationContext:从一个或多个基于java的配置类中加载上下文定义,适用于java注解的方式;

② ClassPathXmlApplicationContext:从类路径下的一个或多个xml配置文件中加载上下文定义,适用于xml配置的方式;

③ FileSystemXmlApplicationContext:从文件系统下的一个或多个xml配置文件中加载上下文定义,也就是说系统盘符中加载

④ AnnotationConfigWebApplicationContext:专门为web应用准备的,适用于注解方式;

⑤ XmlWebApplicationContext:从web应用下的一个或多个xml配置文件加载上下文定义,适用于xml配置方式。

 

那么这么多种的上下文,spring默认用的是哪个呢,我们能在配置中自定义吗?

我们知道,web.xml 的加载顺序是:context-param -> listener -> filter -> servlet

先看监听器。

<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

现在我们进去源码看看。

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
	@Override
	public void contextInitialized(ServletContextEvent event) {
		initWebApplicationContext(event.getServletContext());
	}
}

我们看到ContextLoaderListener继承了ContextLoader,基础扎实的都知道,一个类在加载时,如果存在父类,会先加载父类。这里我们标记下,暂时不管ContextLoader在加载时,做了哪些初始化动作。 

继续看下一步,直接调用父类的函数

public class ContextLoader {
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!");
		}

		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 {
			// Store context in local instance variable, to guarantee that
			// it is available on ServletContext shutdown.
                        //这里开始创建上下文
			if (this.context == null) {
				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);
					}
					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.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;
		}
	}
}

 

这个函数很长,我们只关心创建上下文的语句。

if (this.context == null) {
   this.context = createWebApplicationContext(servletContext);
}

调用的还是ContextLoader类中的函数,继续看

public class ContextLoader {
	protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
		Class<?> contextClass = determineContextClass(sc);
		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);
	}
}

这个函数大概意思是找到上下文的类类型,通过反射创建上下文对象。

那么重点就是这个类类型是怎么决定的,看上面的函数这一句

Class<?> contextClass = determineContextClass(sc);

继续追踪,还是在ContextLoader类。

public class ContextLoader {
protected Class<?> determineContextClass(ServletContext servletContext) {
		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 {
			contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
			try {
				return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
			}
			catch (ClassNotFoundException ex) {
				throw new ApplicationContextException(
						"Failed to load default context class [" + contextClassName + "]", ex);
			}
		}
	}

}

 这个函数是重点,我们来仔细分析。

 
String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);

 先在servletContext中找找是否已配置了上下文。

CONTEXT_CLASS_PARAM是类中的一个常量。

public static final String CONTEXT_CLASS_PARAM = "contextClass";

 

继续往下看。

		if (contextClassName != null) {
			try {
				return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
			}
			catch (ClassNotFoundException ex) {
				throw new ApplicationContextException(
						"Failed to load custom context class [" + contextClassName + "]", ex);
			}
		}

这段代码是说,如果我们已在web.xml中配置了上下文的信息,就通过反射把上下文的类类型返回。那么我们怎么进行配置呢。

回顾下web.xml的加载顺序:context-param -> listener -> filter -> servlet

也就说,如果我们在web.xml中这样配置,就可以自定义我们需要的上下文类型了

	<context-param>
		<param-name>contextClass</param-name>
		<param-value>org.springframework.web.context.support.XmlWebApplicationContext</param-value>
	</context-param>

 

继续回到源码

else {
			contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
			try {
				return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
			}
			catch (ClassNotFoundException ex) {
				throw new ApplicationContextException(
						"Failed to load default context class [" + contextClassName + "]", ex);
			}
		}

这段代码意思是所,如果我们没有配置上下文,就用系统默认的上下文。

那么这个默认上下文是什么呢?

contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());

从源码得知,defaultStrategies是ContextLoader类中的一个属性。

private static final Properties defaultStrategies;

关于Properties类的详细说明就不说了。这里我们只关心defaultStrategies的初始化。

ContextLoader有一段静态代码块对defaultStrategies进行初始。

	static {
		// Load default strategy implementations from properties file.
		// This is currently strictly internal and not meant to be customized
		// by application developers.
		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());
		}
	}

看这一句:

ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);

  DEFAULT_STRATEGIES_PATH也是ContextLoader类的一个常量

private static final String DEFAULT_STRATEGIES_PATH = "ContextLoader.properties";
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);

这段语句是说加载类路径下名称为DEFAULT_STRATEGIES_PATH(其实就是“ContextLoader.properties“”)的属性文件。

我们可以在org.springframework.web.context中找到这样一个文件。

打开ContextLoader.properties看看里面有什么东东。

里面就有一句

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

这就是系统默认定义的上下文了。属性文件会被系统以key和value加载到defaultStrategies对象中。

即defaultStrategies对象会存在这样一对键值

key:org.springframework.web.context.WebApplicationContext

value:org.springframework.web.context.support.XmlWebApplicationContext

 

现在,回到上面代码中这句代码

contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());

可以看到defaultStrategies对象获取这样一个key :WebApplicationContext.class.getName()==org.springframework.web.context.WebApplicationContext

这里就不解释为什么WebApplicationContext.class.getName()==org.springframework.web.context.WebApplicationContext

 

 

至此,所有疑惑都解释完毕

  • 27
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值