SSM项目启动时执行一次该方法 使用ApplicationListener监听方法

在一些业务场景中,当容器初始化完成之后,需要处理一些操作,比如一些数据的加载、初始化缓存、特定任务的注册等等。这个时候我们就可以使用Spring提供的ApplicationListener来进行操作。

springBoot 项目可以参考这篇文章 springboot 启动执行任务CommandLineRunner

package com.zsdn.config;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Component //用于项目启动时发现 也可以用@Service
public class SearchReceive implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if (contextRefreshedEvent.getApplicationContext().getParent() == null) {//保证只执行一次
            //需要执行的方法
            System.out.println("这里就执行了一次哦");
        }

    }
}

在这里插入图片描述
至此 完成 有问题的可以评论区解答 共同学习 ing

发布了89 篇原创文章 · 获赞 47 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43726822/article/details/103706502
今日推荐