ServletContextListener监听Web应用的启动,我们可以在Web应用启动时,就加载 Spring的配置文件,创建应用上下文对象ApplicationContext,在将其存储到最大的域servletContext域中,这样 就可以在任意位置从域中获得应用上下文ApplicationContext对象了。
①导入spring-web坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
②将Spring的应用上下文对象存储到ServletContext域中
public class ContextLoaderListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
ServletContext servletContext = servletContextEvent.getServletContext();
servletContext.setAttribute("app",app);
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
③在web.xml中配置ContextLoaderListener监听器
<listener>
<listener-class>com.text.listener.ContextLoaderListener</listener-class>
</listener>
④获取Spring的应用上下文对象
ServletContext servletContext = this.getServletContext();
//ServletContext servletContext = req.getServletContext();
ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");
UserService userService = (UserService) app.getBean("userService");