前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ApplicationListener 和@EventListener 注解实现事件监听

ApplicationListener 和@EventListener 注解实现事件监听

作者头像
水货程序员
修改2018-12-03 09:29:09
10K0
修改2018-12-03 09:29:09
举报
文章被收录于专栏:javathings

ApplicationListener 和@EventListener 注解实现事件监听

对于 Spring 容器的一些事件,可以监听并且触发相应的方法。通常的方法有 2 种,ApplicationListener 接口和@EventListener 注解。

ApplicationListener 接口

ApplicationListener 接口的定义如下:

代码语言:javascript
复制
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
 
/**
* Handle an application event.
* @param event the event to respond to
*/
void onApplicationEvent(E event);
}

它是一个泛型接口,泛型的类型必须是 ApplicationEvent 及其子类,只要实现了这个接口,那么当容器有相应的事件触发时,就能触发 onApplicationEvent 方法。ApplicationEvent 类的子类有很多,Spring 框架自带的如下几个。

使用方法很简单,就是实现一个 ApplicationListener 接口,并且将加入到容器中就行。

代码语言:javascript
复制
@Component
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {
 
@Override
public void onApplicationEvent(ApplicationEvent event) {
  System.out.println("事件触发:"+event.getClass().getName());
}
}

当 main 方法运行的时候:

代码语言:javascript
复制
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
applicationContext.close();
}

结果如下:

代码语言:javascript
复制
事件触发:org.springframework.context.event.ContextRefreshedEvent
事件触发:org.springframework.context.event.ContextClosedEvent

@EventListener 注解

除了通过实现接口,还可以使用@EventListener 注解,实现对任意的方法都能监听事件。

代码语言:javascript
复制
@Configuration
@ComponentScan(value = "com.learn")
public class Config {
@EventListener(classes={ApplicationEvent.class})
public void listen(ApplicationEvent event){
System.out.println("事件触发:"+event.getClass().getName());
}
} 

在任意方法上标注@EventListener 注解,指定 classes,即需要处理的事件类型,一般就是 ApplicationEven 及其子类,可以设置多项。

结果如下:

代码语言:javascript
复制
事件触发:org.springframework.context.event.ContextRefreshedEvent
事件触发:org.springframework.context.event.ContextClosedEvent
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ApplicationListener 和@EventListener 注解实现事件监听
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档