spring容器启动之我见(二)
来源:互联网 发布:万网域名赎回费用 编辑:程序博客网 时间:2024/05/29 04:54
因为WebApplicationContext 需要ServletContext 实例,也就是说它必须在拥有Web 容器的前提下才能完成启动的工作。有过Web 开发经验的读者都知道可以在web.xml 中配置自启动的Servlet 或定义Web 容器监听器(ServletContextListener),借助这两者中的任何一个,我们就可以完成启动Spring Web 应用上下文的工作。
Spring 分别提供了用于启动WebApplicationContext 的Servlet 和Web 容器监听器:
org.springframework.web.context.ContextLoaderServlet;
org.springframework.web.context.ContextLoaderListener。
两者的内部都实现了启动WebApplicationContext 实例的逻辑,我们只要根据Web 容器的具体情况选择两者之一,并在web.xml 中完成配置就可以了。
你可以查看一下spring3.0的change log 里面注明:
removedContextLoaderServletand Log4jConfigServlet 的确是去掉了
spring有三种启动方式,使用ContextLoaderServlet,ContextLoaderListener和ContextLoaderPlugIn
可以采用余下两种启动方式ContextLoaderListener和ContextLoaderPlugIn 建议使用ContextLoaderListener
ContextLoaderListener相关配置的注意事项看Spring笔记1——控制反转容器
那通过ContextLoaderListener,Spring是怎么怎么初始化和配置Spring容器(WebApplicationContext)的呢?
Spring容器的初始化过程:
接下来再详细从代码上介绍吧
ContextLoaderListener的体系结构
部署spring例子到tomcat,运行tomcat
看到上面spring 和tomcat 结合,我们似乎想到spring和tomcat之间似乎有点什么关系
Tomcat(5.0以上)
加载时的织入配置 Apache Tomcat 缺省的ClassLoader(类装载器)并不支持类的切换, 但是它允许使用用户自定义的类装载器。Spring提供了 TomcatInstrumentableClassLoader 类 (在org.springframework.instrument.classloading.tomcat 包中),这个类继承自Tomcat的类装载器 (WebappClassLoader)并且允许JPA ClassTransformer 的实例来“增强”所有由它加载的类。 简单说,JPA转化器(JPA transformer)仅仅在(使用 TomcatInstrumentableClassLoader 的)特定web应用程序中才能被使用。
为使用用户自定义的类装载器: 将 spring-tomcat-weaver.jar 复制到 $CATALINA_HOME/server/lib 下 (其中$CATALINA_HOME 表示Tomcat的安装路径)。
通过修改web application context使Tomcat使用用户自定义的类装载器(而不是默认的类装载器):
<Context path="/myWebApp" docBase="/my/webApp/location">
<Loader loaderClass="org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader"/>
</Context>
ContextLoader
/**
* Initialize the root web application context.
*/
@Override
public
void
contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
再看一下ContextLoader的initWebApplicationContext()
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);
//这里根据ServletContext创建Spring容器(在这里创建的是XmlWebApplicationContext)
}
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);
//这里进行WebApplicationContext的配置工作,其中包括把servletContext和Spring容器关联起来,以及将配置文件(applicationContext.xml)加入到容器中
}
}
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;
}
}
再进入createWebApplicationContext()
//ContextLoader
protected
WebApplicationContext createWebApplicationContext(ServletContext sc) {
Class<!--?--> contextClass = determineContextClass(sc);
//返回WebApplicationContext实现类使用,默认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);
}
再看determineConetxt()
可以看到在这里其实就是根据Parameter CONTEXT_CLASSPARAM去实例化一个WebApplicatoinContext,而该参数其实在web.xml已经配置为XmlWebApplicationContext(WebApplicationContext实现类) ,看web.xml
//web.xml
<!-- 如果配置了contextClass上下文参数,就会用参数所指定的WebApplicationContext实现类初始话容器 -->
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.XmlWebApplicationContext
</param-value>
</context-param>
接着,我们回到initWebApplicationContext(),其中调用的configureAndRefreshWebApplicationContext(cwac, servletContext);我们看一下他的实现
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);
//这里设置WebApplicationContext的id值为contextId也就是我们浏览器访问的localhost:8080/01/中的01
}
else
{
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
}
wac.setServletContext(sc);
String initParameter = sc.getInitParameter(CONFIG_LOCATION_PARAM);
//这里设置Web.xml中配置的contextConfigLocation参数,也就是配置文件applicationContext.xml了
if
(initParameter !=
null
) {
wac.setConfigLocation(initParameter);
}
customizeContext(sc, wac);
wac.refresh();
//加载刚才的配置文件applicationContext.xml,以及bean的实例化
}
再看一下
//XmlWebApplicationContext
@Override
public
void
refresh()
throws
BeansException, IllegalStateException {
synchronized
(
this
.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try
{
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch
(BeansException ex) {
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw
ex;
}
}
}
这个方法就是配置Spirng Web容器,根据applicationContext.xml实例化类的重中之重了,东西太多了,下篇博客再接着说吧
- spring容器启动之我见(二)
- spring容器启动之我见(一)
- spring容器启动之我见(三)
- spring容器启动之我见(四、获取容器和获取容器中的bean)
- Spring源代码分析之(二):IOC容器在web容器中的启动
- 【Spring】Spring之我见
- Spring整合Struts2之启动Spring容器
- Spring AOP之我见。
- Spring概念之我见
- spring注入之我见
- FEC之我见二
- (二)spring 之IOC容器
- Spring之IoC容器解析(二)
- Spring学习之IOC容器(二)
- spring源码之spring启动二
- web容器启动spring容器
- Spring Security优劣之我见
- 红黑树之我见(二)
- MySQL InnoDB存储引擎参数详解及优化
- Java_基础_不要覆写静态方法
- 练习2: 通过交换函数的实现,学习指针的用法。
- php调试工具---xhprof安装和使用
- [置顶] 最常用的15大Eclipse开发快捷键技巧
- spring容器启动之我见(二)
- Linux下修改终端提示符
- iOS开发 Coretext(文字排版)的基本用法
- Rotate Image 二维数组旋转90度
- 深度学习原理和实践
- 算法面试——二叉树最低公共祖先LCA
- 多线程和多进程的区别(小结)
- Anagrams 寻找相同的乱序的字母排列
- Python 关于 name main的使用 if __name__ == '__main__':