zoukankan      html  css  js  c++  java
  • Springboot项目的应用监听器ApplicationListener的使用

          

    • 背景

    • ApplicationContext事件监听机制是Observer设计模式的实现,通过继承ApplicationEvent类和实现ApplicationListener接口,可以实现ApplicationContext事件处理;
    • 如果容器中存在ApplicationListener的Bean,当ApplicationContext调用publishEvent方法时,对应的监听器Bean会被触发;
    • spring内置事件

      内置事件 描述
      ContextRefreshedEvent ApplicationContext 被初始化或刷新时,该事件被触发。这也可以在 ConfigurableApplicationContext接口中使用 refresh() 方法来发生。此处的初始化是指:所有的Bean被成功装载,后处理Bean被检测并激活,所有Singleton Bean 被预实例化,ApplicationContext容器已就绪可用
      ContextStartedEvent 当使用 ConfigurableApplicationContext (ApplicationContext子接口)接口中的 start() 方法启动 ApplicationContext 时,该事件被发布。你可以调查你的数据库,或者你可以在接受到这个事件后重启任何停止的应用程序。
      ContextStoppedEvent 当使用 ConfigurableApplicationContext 接口中的 stop() 停止 ApplicationContext 时,发布这个事件。你可以在接受到这个事件后做必要的清理的工作。
      ContextClosedEvent 当使用 ConfigurableApplicationContext 接口中的 close() 方法关闭 ApplicationContext 时,该事件被发布。一个已关闭的上下文到达生命周期末端;它不能被刷新或重启。
      RequestHandledEvent 这是一个 web-specific 事件,告诉所有 bean HTTP 请求已经被服务。只能应用于使用DispatcherServlet的Web应用。在使用Spring作为前端的MVC控制器时,当Spring处理用户请求结束后,系统会自动触发该事件。

       同样事件可以自定义、监听也可以自定义,完全根据自己的业务逻辑来处理。


    • 应用场景:

    • (1)发送邮件   (2)父子任务信息传递   (3)动态日志的存储
    • 监听器ApplicationListen监听器的使用
      @Component// 此注解会将监听器类注册到 Spring的 应用容器中
      public class SecurityListener implements ApplicationListener<ApplicationEvent> {
          @Autowired
          private PoliceAfterHander policeAfterHander;
          @Override
          public void onApplicationEvent(ApplicationEvent applicationEvent ) {
      // 判断事件具体是哪一类事件
      if (applicationEvent instanceof RepubicEvent){ System.out.println("侦察车监听到通共事件。。。");
      //事件监听后处理 policeAfterHander.onAfterHander(); } } }
    • 应用事件ApplicationEvent抽象类的使用
      //自定义事件:通共事件
      public
      class RepubicEvent extends ApplicationEvent { private Actor actor; private String message; public RepubicEvent(Object source) { super(source); } public RepubicEvent(Actor actor,String message) { super(new Object()); this.actor = actor; this.message = message; } }
    • 监听结果后的动作处理
    • @Component //作为bean注入到Spring容器中
      public class PoliceAfterHander {
          public void onAfterHander(){
              System.out.println("王柯达带领刑警一处进行抓捕行动。。。");
          }
      }
  • 相关阅读:
    Axure RP使用攻略--动态面板滑动效果(10)
    Axure RP使用攻略--带遮罩层的弹出框(9)
    Axure RP使用攻略--动态面板的用途(8)
    Axure RP使用攻略--入门级(七)之axure元件使用思路的补充
    Axure RP使用攻略--入门级(六)关于Axure rp触发事件中IF和ELSE IF的使用说明
    Axure RP使用攻略--入门级(五)系统函数与变量
    Axure RP使用攻略--入门级(四)条件生成器
    Axure RP使用攻略--入门级(三)元件的触发事件
    Altium Designer 14安装破解
    小米手环暴力拆解
  • 原文地址:https://www.cnblogs.com/parrot/p/14058103.html
Copyright © 2011-2022 走看看