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

使用Listener准备application作用域数据的小问题

时间:2014-05-02 06:43:34      阅读:405      评论:0      收藏:0      [点我收藏+]

标签:des   blog   class   code   java   ext   

在程序中,有些数据我们希望在程序启动的时候就准备好,并且只准备一次,放在application作用域中,这时候,我们通常会用Listener来准备这些数据。但是,用Listener准备application作用域的数据,在获取容器的时候会有一些小问题。

public class InitListener implements ServletContextListener {

	//该Listener配置在web.xml里,默认通过反射生成实例,来得到这个对象实例来执行
	//并没有从Spring容器里面获取,Tomcat没有找Spring容器,所以此处无法使用注解
	//如果使用注解,会生成两个对象,一个Tomcat产生的对象,一个Spring容器注入的对象
	//Tomcat会使用自己产生的对象,而Spring管理的对象没人使用
	public void contextInitialized(ServletContextEvent sce) {
		// 获取全局唯一的容器对象,即在web.xml中配置的由Spring的ContextLoaderListener生成的那个容器
		//方法1:ApplicationContext ac = sce.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		
		//方法2:
		//其中getWebApplicationContext(sce.getServletContext())会自动以ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE为key把该容器对象找出来
		ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
		//通过容器拿到Service对象
		PrivilegeService privilegeService = (PrivilegeService) ac.getBean("privilegeServiceImpl");

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

	public void contextDestroyed(ServletContextEvent arg0) {

	}


使用Listener准备application作用域数据的小问题,布布扣,bubuko.com

使用Listener准备application作用域数据的小问题

标签:des   blog   class   code   java   ext   

原文地址:http://blog.csdn.net/v123411739/article/details/24852175

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