如何在web.xml中配置,使tomcat容器加载时能初始化Spring的IOC容器?
可以通过ContextLoaderListener监听器的配置,实现在tomcat容器加载时初始化Spring的IOC容器。
ContextLoaderListener
这个监听器的源代码如下,他继承自ContextLoader,实现了ServletContextListener接口,一个典型的适配器模式。ServletContextListener会监听web容器的生命周期,当容器启动时,会调用监听器的contextInitialized,当容器销毁时就会调用contextDestroyed,因此可以在监听器的这两个方法内,做一些操作。
ContextLoaderListener用于监听tomcat容器,启动时调用contextInitialized来初始化Web环境的IOC容器的上下文,在tomcat关闭时做IOC容器的销毁操作。
具体的细节,不在这里说,明天详细讲解。
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
private ContextLoader contextLoader;
public ContextLoaderListener() {
}
public ContextLoaderListener(WebApplicationContext context) {
super(context);
}
public void contextInitialized(ServletContextEvent event) {
this.contextLoader = this.createContextLoader();
if (this.contextLoader == null) {
this.contextLoader = this;
}
this.contextLoader.initWebApplicationContext(event.getServletContext());
}
/** @deprecated */
@Deprecated
protected ContextLoader createContextLoader() {
return null;
}
/** @deprecated */
@Deprecated
public ContextLoader getContextLoader() {
return this.contextLoader;
}
public void contextDestroyed(ServletContextEvent event) {
if (this.contextLoader != null) {
this.contextLoader.closeWebApplicationContext(event.getServletContext());
}
ContextCleanupListener.cleanupAttributes(event.getServletContext());
}
}
ServletContextListener
ServletContextListener是一个事件监听器,用来监听ServletContextEvent这个事件,这个事件在容器启动和销毁时触发。
ServletContext是什么?
在ContextLoaderListener的contextInitialized中可以看到,在触发事件时,监听器可以直接得到事件对象,通过事件对象中的getServletContext方法取得的ServletContext对象来参与容器上下文的初始化。
那么getServletContext取得的ServletContext是什么呢?
简单来说:
他就是一个工程的全局对象,称之为Servlet上下文,他是工程中全局唯一共享的对象。工程内所有的Servlet都共享这个上下文对象。
可以使用他来获取全局配置参数、资源文件等,他可以持有各个servlet的上下文对象。