前文:Spring提供了一个监听器ContextLoaderListener,该监听器内部加载spring配置文件,创建上下文对象,并存储到ServletContext域中,提供了一个客户端工具WebApplicationContextUtils供使用者获得应用上下文对象。就可以使得spring配置文件applicationContet.xml在teomcat中只需要实例化一次,就可以全局调用。避免了每次getBean()都要new一个ApplicatinContext。
结构:
1.导入spring-web坐标
org.springframework spring-web5.0.5.RELEASE
2.在web资源文件web.xml中配置spring容器的监听器ContextLoaderListener
org.springframework.web.context.ContextLoaderListener
3.在web.xml中设置全局参数,告诉监听器ContextLoaderListener要加载的配置文件的名称路径
contextConfigLocation classpath:applicationContext.xml
注意
web.xml:
contextConfigLocation classpath:applicationContext.xml org.springframework.web.context.ContextLoaderListener UseServlet com.web.UseServlet UseServlet /useServlet
4.UseServlet
public class UseServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
//ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
UseService useService = (UseService) app.getBean("useService");
useService.save();
}
}
手动设置监听器是配置文件在tomcat在加载时就创建在ServletContext域中,这个域很大。
public class ContextLoadListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
ApplicationContext app=new ClassPathXmlApplicationContext("");
ServletContext servletContext = servletContextEvent.getServletContext();
servletContext.setAttribute("app",app);
System.out.println("初始化创建完毕...");
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
public class UseServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");
ApplicationContext app = //WebApplicationContextUtils.getWebApplicationContext(servletContext);
UseService useService = (UseService) app.getBean("useService");
useService.save();
}
}



