public class ContextLoaderListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext servletContext = sce.getServletContext();
// 读取web.xml中的全局参数
String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);
// 将spring的应用上下文对象存储到最大的ServletContext域中
servletContext.setAttribute("app",app);
System.out.println("spring容器创建完毕");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
获取Spring容器方法
public class WebApplicationContextUtils {
public static ApplicationContext getWebApplicationContext(ServletContext servletContext){
return (ApplicationContext) servletContext.getAttribute("app");
}
}