在一些業務場景中,當容器初始化完成之後,需要處理一些操作,比如一些數據的加載、初始化緩存、特定任務的註冊等等。這個時候我們就可以使用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