Java程序初始化啟動(dòng)自動(dòng)執(zhí)行的三種方式
Java程序初始化啟動(dòng)自動(dòng)執(zhí)行的三種方式
@PostConstruct注解
將此注解加在要執(zhí)行的方法上,則程序初始化啟動(dòng)的時(shí)候,會(huì)執(zhí)行此方法,一般用來初始化必要的程序初始信息
注意:
加了postconstruct注解的方法,如果執(zhí)行失敗,整個(gè)程序會(huì)無法正常啟動(dòng)!這個(gè)方法執(zhí)行不完,整個(gè)程序也啟動(dòng)不了?。?!
詳情請(qǐng)看我的錯(cuò)誤總結(jié) 開發(fā)錯(cuò)誤總結(jié)---@PostConstruct注解導(dǎo)致的程序無法啟動(dòng)(@PostConstruct的執(zhí)行)
開始試驗(yàn):
- 啟動(dòng)類
@SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class,args); } }
- 測試類
@Service @Slf4j public class PostConstructTest { @PostConstruct public void testPostConstruct () { log.info("程序初始化執(zhí)行"); } }
- 啟動(dòng)看效果
CommandLineRunner接口
- 實(shí)現(xiàn) CommandLineRunner接口
@Slf4j @Component public class InitCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { log.info("實(shí)現(xiàn)CommandLineRunner接口的程序初始化"); } }
- 啟動(dòng)看效果
ApplicationRunner 接口
- 實(shí)現(xiàn) ApplicationRunner 接口
@Component @Slf4j public class InitApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { log.info("實(shí)現(xiàn)ApplicationRunner接口程序初始化"); } }
- 啟動(dòng)看效果
@Order注解設(shè)置啟動(dòng)順序
我們給前兩個(gè)實(shí)現(xiàn)ApplicationRunner 接口和CommandLineRunner 接口的啟動(dòng)類設(shè)置啟動(dòng)順序
- 為了讓效果明顯一點(diǎn),我們讓程序執(zhí)行完第一個(gè)之后睡眠一下
@Slf4j @Component @Order(value = 1) public class InitCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { log.info("實(shí)現(xiàn)CommandLineRunner接口的程序初始化"); Thread.sleep(2000); } }
@Component @Slf4j @Order(value = 2) public class InitApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { log.info("實(shí)現(xiàn)ApplicationRunner接口程序初始化"); } }
- 執(zhí)行一下來看效果
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java高級(jí)之虛擬機(jī)加載機(jī)制的實(shí)例講解
下面小編就為大家分享一篇Java高級(jí)之虛擬機(jī)加載機(jī)制的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2017-12-12java中InputStream轉(zhuǎn)為MultipartFile的解決方案
這篇文章主要介紹了java中InputStream轉(zhuǎn)為MultipartFile的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-03-03詳解java爬蟲jsoup解析多空格class數(shù)據(jù)
在本篇內(nèi)容中小編給大家分享了java爬蟲jsoup怎么解析多空格class數(shù)據(jù)的方法和技巧,需要的朋友們跟著學(xué)習(xí)下。2018-12-12IDEA提示內(nèi)存不足 low memory的完美解決方法(親測好用)
這篇文章主要介紹了IDEA提示內(nèi)存不足 low memory的完美解決方法(親測好用),這里以IDEA2022版本為例,在IDE中 幫助(help)–>change memory setting(改變內(nèi)存設(shè)置),具體設(shè)置辦法文中給大家詳細(xì)講解,需要的朋友可以參考下2023-01-01spring data jpa 查詢自定義字段,轉(zhuǎn)換為自定義實(shí)體方式
這篇文章主要介紹了spring data jpa 查詢自定義字段,轉(zhuǎn)換為自定義實(shí)體方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06