导航

spring监听器

Posted on 2019-06-24 20:07  cdeelen  阅读(297)  评论(0编辑  收藏  举报

当我们希望在web容器启动时,就加载部分不需要经常修改的信息到ServletContext时可以配置ServletContextListener web启动监听器来完成。实现ServletContextListener 重写contextInitialized、contextDestroyed方法自定义WEB容器启动执行的代码。

在此之前必须启动spring容器,此时可以配置ContextLoaderListener来实现。

ContextLoaderListener作用:在启动web容器时,自动装配Spring application.xml的配置信息。即是在web容器启动时读取spring配置文件,启动spring容器并创建对象放在spring容器中。

启动spring容器需要指定配置文件或者配置类,如果使用注解配置,还需要将spring容器转换为支持注解,但是ContextLoaderListener不支持初始化参数,所以必须配置全局参数。

<!-- 问题:数据初始化监听器要注入Spring容器的对象,必须要再Spring容器先启动才能启动 -->
<!-- 解决方案:使用监听器来启动Spring框架 -->
<!-- 问题:Spring框架启动需要哪些参数 -->
<!-- 1.需要指定配置文件或者配置类的位置 -->
<!-- 2.如果使用的是注解的配置类,需要修改容器的类型 -->
<!-- 问题:监听器是不支持初始化参数的。参数如何传递到监听器里面? -->
<!-- 答:通过设置在全局上下文参数里面,ContextLoaderListener监听器是通过获得上下文参数来解决这个问题的 -->

<context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>org.chu.config</param-value>
    </context-param>
    <context-param>
       <param-name>contextClass</param-name>
       <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </context-param>
    <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

实现ServletContextListener

public class DataInitializeListener implements ServletContextListener  {
    
    //问题:Spring的依赖注入只能在Spring容器中的对象使用。而监听器不是Spring容器的对象。
    //解决方法:在非容器里的对象获得容器里面的对象,容器对象.getBean();

    /**
     * 上下文初始化的时候调用的方法
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
    
     System.out.println("==启动啦==");
     ServletContext context = sce.getServletContext();
     WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(context);
     RoleService roleService = applicationContext.getBean(RoleService.class);
     DictionaryService dictionaryService = applicationContext.getBean(DictionaryService.class);
     //获得权限
     //获得角色
     List<Map<String, Object>> roles = roleService.findAllRole();
     context.setAttribute("global_roles", roles);
     //数据字典
     List<Map<String, Object>> dictionarys = dictionaryService.findAllDictionary();
     context.setAttribute("global_dictionarys", dictionarys);
     //获得模块
        
    }

    /**
     * 上下文销毁的时候调用的方法
     */
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("==关闭了==");
        ServletContext context = sce.getServletContext();
        context.removeAttribute("global_roles");
        context.removeAttribute("global_dictionarys");
        
    }

}

配置ServletContextListener实现类

<listener>
       <listener-class>org.chu.listener.DataInitializeListener</listener-class>
 </listener>