【转】监听上下文初始化过程

实现javax.servlet.ServletContextListener接口即可监听ServletContext创建过程中的两个关键事件:初始化和销毁
ServletContextListener.java源代码:
//Compiled from ServletContextListener.java (version 1.2 : 46.0, no super bit)
public abstract interface javax.servlet.ServletContextListener extends java.util.EventListener {
  
  // Method descriptor #5 (Ljavax/servlet/ServletContextEvent;)V
  public abstract void contextInitialized(javax.servlet.ServletContextEvent arg0);
  
  // Method descriptor #5 (Ljavax/servlet/ServletContextEvent;)V
  public abstract void contextDestroyed(javax.servlet.ServletContextEvent arg0);
}



ServletContextListener 实现类

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());
		}
	}
}

你可能感兴趣的:(java)