创建ContextLoadListener类:
public class ContextLoaderListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
//将Spring的应用上下文对象存储到ServletContext域中
ServletContext servletContext = servletContextEvent.getServletContext();
servletContext.setAttribute("app",app);
System.out.println("Spring容器创建完毕。。。。。。");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
并在web.xml中配置监听器
<!--配置监听器-->
<listener>
<listener-class>com.listener.ContextLoaderListener</listener-class>
</listener>
之后在HttpServlet的继承类中就可以用
ServletContext servletContext = this.getServletContext();
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
UserService bean = webApplicationContext.getBean(UserService.class);
来获取注入的Bean内容