您的位置:首页 > 移动开发

使用Listener准备application作用域数据

2016-03-29 17:37 288 查看
在程序中。有些数据我们希望在程序启动的时候就准备好,而且仅仅准备一次,放在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) {

}


该Listener配置在web.xml里,默认通过反射生成实例,来得到这个对象实例来运行
并没有从Spring容器里面获取,Tomcat没有找Spring容器,所以此处无法使用注解
假设使用注解,会生成两个对象,一个Tomcat产生的对象,一个Spring容器注入的对象
Tomcat会使用自己产生的对象,而Spring管理的对象没人使用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: