创建listener实现ServletContext接口
public class SpringServletContextListener implements ServletContextListener {
// Public constructor is required by servlet spec
public SpringServletContextListener() {
}
// -------------------------------------------------------
// ServletContextListener implementation
// -------------------------------------------------------
public void contextInitialized(ServletContextEvent sce) {
// 1获取spring配置文件的名称
ServletContext servletContext = sce.getServletContext();
String config = servletContext.getInitParameter("ConfigLocation");
//1.创建IOC容器
ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
// 2.将IOC容器放入servletContext一个属性中
}
public void contextDestroyed(ServletContextEvent sce) {
/* This method is invoked when the Servlet Context
(the Web application) is undeployed or
Application Server shuts down.
*/
}
}
在web.xml文件中配置listener和<context-param>属性
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <!--配置spring配置文件的名称和位置--> <context-param> <param-name>ConfigLocation</param-name> <param-value>applicationContext.xml</param-value> </context-param> <!--启动IOC容器的servletContextListener--> <listener> <listener-class>com.marry.spring.struts2.listeners.SpringServletContextListener</listener-class> </listener> </web-app>
转载于:https://blog.51cto.com/malin/1842767