Springboot啟動后立即某個執(zhí)行方法的四種方式
最新需要在項目啟動后立即執(zhí)行某個方法,然后特此記錄下找到的四種方式
注解@PostConstruct
使用注解@PostConstruct是最常見的一種方式,存在的問題是如果執(zhí)行的方法耗時過長,會導致項目在方法執(zhí)行期間無法提供服務。
@Component
public class StartInit {
//
// @Autowired 可以注入bean
// ISysUserService userService;
@PostConstruct
public void init() throws InterruptedException {
Thread.sleep(10*1000);//這里如果方法執(zhí)行過長會導致項目一直無法提供服務
System.out.println(123456);
}
}
CommandLineRunner接口
實現CommandLineRunner接口 然后在run方法里面調用需要調用的方法即可,好處是方法執(zhí)行時,項目已經初始化完畢,是可以正常提供服務的。
同時該方法也可以接受參數,可以根據項目啟動時: java -jar demo.jar arg1 arg2 arg3 傳入的參數進行一些處理。詳見: Spring boot CommandLineRunner啟動任務傳參
@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println(Arrays.toString(args));
}
}
實現ApplicationRunner接口
實現ApplicationRunner接口和實現CommandLineRunner接口基本是一樣的。
唯一的不同是啟動時傳參的格式,CommandLineRunner對于參數格式沒有任何限制,ApplicationRunner接口參數格式必須是:–key=value
@Component
public class ApplicationRunnerImpl implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
Set<String> optionNames = args.getOptionNames();
for (String optionName : optionNames) {
List<String> values = args.getOptionValues(optionName);
System.out.println(values.toString());
}
}
}
實現ApplicationListener
實現接口ApplicationListener方式和實現ApplicationRunner,CommandLineRunner接口都不影響服務,都可以正常提供服務,注意監(jiān)聽的事件,通常是ApplicationStartedEvent 或者ApplicationReadyEvent,其他的事件可能無法注入bean。
@Component
public class ApplicationListenerImpl implements ApplicationListener<ApplicationStartedEvent> {
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
System.out.println("listener");
}
}
四種方式的執(zhí)行順序
注解方式@PostConstruct 始終最先執(zhí)行
如果監(jiān)聽的是ApplicationStartedEvent 事件,則一定會在CommandLineRunner和ApplicationRunner 之前執(zhí)行。
如果監(jiān)聽的是ApplicationReadyEvent 事件,則一定會在CommandLineRunner和ApplicationRunner 之后執(zhí)行。
CommandLineRunner和ApplicationRunner 默認是ApplicationRunner先執(zhí)行,如果雙方指定了@Order 則按照@Order的大小順序執(zhí)行,大的先執(zhí)行。
總結
到此這篇關于Springboot啟動后立即某個執(zhí)行方法的四種方式的文章就介紹到這了,更多相關Springboot啟動后執(zhí)行方法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
基于JavaSwing+mysql開發(fā)一個學生社團管理系統(tǒng)設計和實現
項目使用Java swing+mysql開發(fā),可實現基礎數據維護、用戶登錄注冊、社團信息列表查看、社團信息添加、社團信息修改、社團信息刪除以及退出注銷等功能、界面設計比較簡單易學、適合作為Java課設設計以及學習技術使用,需要的朋友參考下吧2021-08-08
詳解java.lang.reflect.Modifier.isInterface()方法
這篇文章主要介紹了詳解java.lang.reflect.Modifier.isInterface()方法的相關資料,這里提供實例幫助大家理解這個方法的使用,需要的朋友可以參考下2017-09-09

