码迷,mamicode.com
首页 > 移动开发 > 详细

使用Listener准备application作用域数据

时间:2015-06-02 18:08:38      阅读:253      评论:0      收藏:0      [点我收藏+]

标签:java   hibernate   encoding   myeclipse   java web   

在程序中,有些数据我们希望在程序启动的时候就准备好,并且只准备一次,放在application作用域中,这时候,我们通常会用Listener来准备这些数据。但是,用Listener准备application作用域的数据,在获取容器的时候会有一些注意事项。
public class InitListener implements ServletContextListener {


	public void contextInitialized(ServletContextEvent sce) {
		// 获取容器与相关的Service对象
		ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
		PrivilegeService privilegeService = (PrivilegeService) ac.getBean("privilegeServiceImpl");

		// 准备数据:topPrivilegeList
		List<Privilege> topPrivilegeList = privilegeService.findTopList();
		sce.getServletContext().setAttribute("topPrivilegeList", topPrivilegeList);
		System.out.println("------------> 已准备数据 <------------");
		// 准备数据:allPrivilegeUrls
				Collection<String> allPrivilegeUrls = privilegeService.getAllPrivilegeUrls();
				sce.getServletContext().setAttribute("allPrivilegeUrls", allPrivilegeUrls);
				System.out.println("------------> 已准备数据allPrivilegeUrls <------------");
	}

	public void contextDestroyed(ServletContextEvent arg0) {

	}
  1. 该Listener配置在web.xml里,默认通过反射生成实例,来得到这个对象实例来执行  
  2.  并没有从Spring容器里面获取,Tomcat没有找Spring容器,所以此处无法使用注解  
  3.   如果使用注解,会生成两个对象,一个Tomcat产生的对象,一个Spring容器注入的对象  
  4.  Tomcat会使用自己产生的对象,而Spring管理的对象没人使用 

使用Listener准备application作用域数据

标签:java   hibernate   encoding   myeclipse   java web   

原文地址:http://blog.csdn.net/u013370108/article/details/46328277

(1)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!