栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring ApplicationListener的使用详解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring ApplicationListener的使用详解

介绍

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

ContextRefreshedEvent事件监听

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

@Component
public class LearnListener implements ApplicationListener {
  @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 {
  @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("发送结束");
  }
}

结果

到此这篇关于Spring ApplicationListener的使用详解的文章就介绍到这了,更多相关Spring ApplicationListener 内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/133795.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号