zoukankan      html  css  js  c++  java
  • 使用Listener准备application作用域数据

    在程序中。有些数据我们希望在程序启动的时候就准备好,而且仅仅准备一次,放在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管理的对象没人使用 

  • 相关阅读:
    07 JavaWeb
    06 XML编程(CRUD)
    05 XML
    04 DOM一窥
    03 Javascript初识
    02 CSS/javaScript
    01 HTML基础
    09_IO流
    08_集合概述
    07_基本数据类型和包装类
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/5333821.html
Copyright © 2011-2022 走看看