ContextRefreshedEvent事件使用注意事项(Spring)

0 概述
ContextRefreshedEvent 事件会在Spring容器初始化完成会触发该事件。我们在实际工作也可以能会监听该事件去做一些事情,但是有时候使用不当也会带来一些问题。

1 防止重复触发
主要因为对于web应用会出现父子容器,这样就会触发两次,那么如何避免呢?下面给出一种简单的解决方案。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Component
public class TestTask implements ApplicationListener<ContextRefreshedEvent> {
    private volatile AtomicBoolean isInit=new AtomicBoolean(false);
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //防止重复触发
        if(!isInit.compareAndSet(false,true)) {
            return;
        }
        start();
    }
 
    private void start() {
        //开启任务
        System.out.println("****-------------------init---------------******");
    }
}

  

2 监听事件顺序问题

Spring 提供了一个SmartApplicationListener类,可以支持listener之间的触发顺序,普通的ApplicationListener优先级最低(最后触发)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@Component
public class LastTask implements SmartApplicationListener {
    private volatile AtomicBoolean isInit = new AtomicBoolean(false);
    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return eventType == ContextRefreshedEvent.class;
    }
 
    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return true;
    }
 
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (!isInit.compareAndSet(false, true)) {
            return;
        }
        start();
    }
 
    private void start() {
        //开启任务
        System.out.println("LastTask-------------------init------------ ");
    }
 
    //值越小,就先触发
    @Override
    public int getOrder() {
        return 2;
    }
}

  

posted @   尐鱼儿  阅读(3963)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示