zoukankan      html  css  js  c++  java
  • Spring ApplicationListenner 使用初步探索

    Spring ApplicationListenner 是事件机制的一部分,与ApplicationEvent抽象类结合完成ApplicationContext的事件

    ContextRefreshedEvent事件监听

     

    以Spring的内置事件ContextRefreshedEvent为例,当ApplicationContext被初始化或刷新时,会触发ContextRefreshedEvent事件.如下代码示例:

     
    @Component
    public class LearnListener implements ApplicationListener<ContextRefreshedEvent> {
      @Override
      public void onApplicationEvent(ContextRefreshedEvent event) {
       //获取所有的bean
       String[] definitionNames = event.getApplicationContext().getBeanDefinitionNames();
       for (String name : definitionNames) {
         //打印名称
         System.out.println("name = " + name);
       }
      }
    }

    自定义事件

     

    public class MyEvent extends ApplicationEvent {
      
      private Long id;
      private String message;
      public MyEvent(Object source) {
        super(source);
      }
     
      public MyEvent(Object source, Long id, String message) {
        super(source);
        this.id = id;
        this.message = message;
      }
      //get set 方法省略
    }
     @Component
    public class MyListener implements ApplicationListener<MyEvent> {
      @Override
      public void onApplicationEvent(MyEvent event) {
        System.out.println("监听到事件: "+event.getId()+"	"+event.getMessage());
      }
    }
    

     

    @SpringBootTest
    @RunWith(SpringRunner.class)
    public class ListenerTest {
      @Autowired
      private ApplicationContext applicationContext;
     
      @Test
      public void testListenner() {
        MyEvent myEvent = new MyEvent("myEvent", 9527L, "十二点了 该吃饭了~");
        applicationContext.publishEvent(myEvent);
       // System.out.println("发送结束");
      }
    }

     

  • 相关阅读:
    Java WebService入门实例
    Maven是什么
    for 循环
    2.4 DevOps工程师的故事:构建运行时的严谨性
    2.3.3 构建微服务的入口:Spring Boot控制器
    2.3.2 引导Spring Boot应用程序:编写引导类
    2.1.3 互相交流:定义服务接口
    第2章 使用Spring Boot构建微服务
    第1章 欢迎来到Cloud和Spring
    第一次在博客园开博
  • 原文地址:https://www.cnblogs.com/dousil/p/14636194.html
Copyright © 2011-2022 走看看