Spring IOC容器如何与web容器建立联系,使得在web环境下能运用Spring 容器去管理对象,这要从web.xml配置文件中的ContextLoaderListener说起。它是Spring容器与web容器建立联系的入口,这里就先抛砖引玉啦。
先来看看web.xml配置文件中的
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/spring-context.xml,
classpath:spring/spring-datasource.xml,
classpath:spring/spring-context-shiro.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
这个大家一字很熟悉,这便是Spring容器与web容器建立联系的入口。来看看ContextLoaderListener的源码
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
public ContextLoaderListener() {
}
public ContextLoaderListener(WebApplicationContext context) {
super(context);
}
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
@Override
public void contextDestroyed(ServletContextEvent event) {
closeWebApplicationContext(event.getServletContext());
ContextCleanupListener.cleanupAttributes(event.getServletContext());
}
}
可以看到其实现了ServletContextListener 接口,这样便可以从web.xml文件中加载ServletContext一些配置信息,兼听ServletContext上下文的变化情况。ServletContextListener 有两个方法contextInitialized 与contextDestroyed,contextInitialized 在容器启动时调用,contextDestroyed在容器关闭前调用。 可以看到在ContextLoaderListener中 contextInitialized 内部调用了父类ContextLoader 的initWebApplicationContext方法,这便是Spring容器初始化的入口。
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
//判断是否已初始化过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!");
}
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) {
//创建Spring容器,默认情况下为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);
}
//配置Spring容器,加载servletContext的一些配置文件
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
//将WebApplicationContext对象保存在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;
}
这里忽视一些细节,重点看看initWebApplicationContext方法中
- this.context = createWebApplicationContext(servletContext);
- configureAndRefreshWebApplicationContext(cwac, servletContext); 3.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
createWebApplicationContext //创建Spring容器,默认情况下为XmlWebApplicationContext this.context = createWebApplicationContext(servletContext) context是ContextLoader的成员变量,其类型为WebApplicationContext,WebApplicationContext续承ApplicationContext为Spring的容器。 再来看看源码
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
//采用什么类型的FactoryBean创建Spring 容器
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);
}
再看determineContextClass源码
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);
}
}
}
默认情况下在web.xml中不会设置SevletContext的contextClass参数,便根据defaultStrategies.getProperty(WebApplicationContext.class.getName())查找Spring容器对应的实现类。 defaultStrategies为ContextLoader的类型为Properties的静态成员变量,ContextLoader内有一个静态初始化块对其进行初始化。
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这个路径的文件,实际上是ClassPathResource将到ContextLoader包对应的路径下面找到ContextLoader.properties文件。
再打ContextLoader.properties看看其内容:
可以看到前面说的Spring容器的默认实现类XmlWebApplicationContext,最后这个通过反射createWebApplicationContext将返回XmlWebApplicationContext的对象给ContextLoader的成员变量context。 到这里**1. this.context = createWebApplicationContext(servletContext);**分析结束。
再来看看**2. configureAndRefreshWebApplicationContext(cwac, servletContext);**的分析 configureAndRefreshWebApplicationContext源码:
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
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);
//得到web.xml中ServletContext参数contextConfigLocation对应的配置信息
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
//将配置信息进行解析并设置
wac.setConfigLocation(configLocationParam);
}
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}
customizeContext(sc, wac);
//Spring容器真正初始化的地方
wac.refresh();
}
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
这行代码将得到在web.xml中的Spring配置文件的信息,就是一开始 的web.xml的这部分
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/spring-context.xml,
classpath:spring/spring-datasource.xml,
classpath:spring/spring-context-shiro.xml
</param-value>
</context-param>
再来分析一下**wac.setConfigLocation(configLocationParam)**这行代码 从上面的分析知道默认情况下wac为XmlWebApplicationContext类型的对象。 在XmlWebApplicationContext的父类AbstractRefreshableWebApplicationContext实现了ConfigurableWebApplicationContext接口,而另一方面AbstractRefreshableWebApplicationContext又续承了AbstractRefreshableConfigApplicationContext类。AbstractRefreshableConfigApplicationContext类里面实现了setConfigLocation方法。
public void setConfigLocation(String location) {
setConfigLocations(StringUtils.tokenizeToStringArray(location, CONFIG_LOCATION_DELIMITERS));
}
String CONFIG_LOCATION_DELIMITERS = ",; \t\n"; 从这里可以看出,在web.xml里面设置contextConfigLocation的param-value时,可以用",; \t\n"来分隔多个配置文件。
public void setConfigLocations(String... locations) {
if (locations != null) {
Assert.noNullElements(locations, "Config locations must not be null");
this.configLocations = new String[locations.length];
for (int i = 0; i < locations.length; i++) {
this.configLocations[i] = resolvePath(locations[i]).trim();
}
}
else {
this.configLocations = null;
}
}
再回到configureAndRefreshWebApplicationContext方法中wac.refresh()这一行,这才是Spring容器真正初始化的地方,由于后面涉及的东西比较多将在后面专门分析一下。 到这里2. configureAndRefreshWebApplicationContext(cwac, servletContext);的分析结束。 再来看看3.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); 这个比较简单就是将上面用反射方法创建的XmlWebApplicationContext对象保存在ServletContext上下文中。由于本人水平有限不正确的地方,欢迎大家指正。
来源:oschina
链接:https://my.oschina.net/u/1421030/blog/730719