spring事件监听器系列一:应用

这篇博客介绍了Spring事件监听器的使用,包括通过@EventListener注解和实现ApplicationListener接口两种方式声明监听器。示例展示了如何监听Spring容器启动事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这篇笔记主要记录spring事件监听器的应用demo
在spring中,声明一个事件监听者有两种方式:
1.注解:@EventListener
2.实现ApplicationListener接口

代码

appConfig配置类

@Configuration
@ComponentScan("com.spring.publishevent")
public class AppConfig {

}

通过@EventListener注解声明一个事件监听者

@Component
public class ContextRefreshEventListener {

    @EventListener(ContextRefreshedEvent.class)
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent){
        System.out.println("通过注解方式声明一个监听者:接收到容器启动事件");
    }
}

通过实现ApplicationListener接口来声明一个事件监听者

@Component
public class ContextRefreshEventListenerInterface implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("通过实现接口声明一个事件监听者,接收到容器启动消息:");
    }
}

由于我模拟监听的是spring容器启动事件,所以,只需要有下面这一行代码即可

public class EventTest {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值