欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Spring ApplicationListener的使用详解

时间:2021-01-10 11:02:33|栏目:JAVA代码|点击:

介绍

Spring ApplicationListener 是Spring事件机制的一部分,与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);
   }
  }
}

自定义事件

代码

//继承ApplicationEvent 抽象类就可以自定义事件模型
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 方法省略
}

//实现ApplicationListener接口
  @Component
public class MyListener implements ApplicationListener<MyEvent> {
  @Override
  public void onApplicationEvent(MyEvent event) {
    System.out.println("监听到事件: "+event.getId()+"\t"+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("发送结束");
  }
}

结果

上一篇:简单了解SpringCloud运行原理

栏    目:JAVA代码

下一篇:Java Map 按照Value排序的实现方法

本文标题:Spring ApplicationListener的使用详解

本文地址:http://www.codeinn.net/misctech/42974.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有