【转】监听上下文初始化过程
实现javax.servlet.ServletContextListener接口即可监听ServletContext创建过程中的两个关键事件:初始化和销毁
import javax.servlet.ServletContextEvent;import org.springframework.web.context.ContextLoader;import org.springframework.web.context.WebApplicationContext;public class MyServletContextListener implements javax.servlet.ServletContextListener {private ContextLoader contextLoader;/** * Initialize the root web application context. */public void contextInitialized(ServletContextEvent event) {this.contextLoader = createContextLoader();//取得上下文WebApplicationContext context = this.contextLoader.initWebApplicationContext(event.getServletContext());/* * 从这里开始,就可以使用上下文context了 * 例如:为MyBeanFactory注入context,使MyBeanFactory可以利用context取得dataSource等 * MyBeanFactory.setContext(context); */}/** * Create the ContextLoader to use. Can be overridden in subclasses. * * @return the new ContextLoader */protected ContextLoader createContextLoader() {return new ContextLoader();}/** * Return the ContextLoader used by this listener. */public ContextLoader getContextLoader() {return contextLoader;}/** * Close the root web application context. */public void contextDestroyed(ServletContextEvent event) {if (this.contextLoader != null) {this.contextLoader.closeWebApplicationContext(event.getServletContext());}}}