溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Springboot啟動后怎么執(zhí)行

發(fā)布時間:2023-04-17 10:44:34 來源:億速云 閱讀:105 作者:iii 欄目:開發(fā)技術

這篇文章主要介紹了Springboot啟動后怎么執(zhí)行的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇Springboot啟動后怎么執(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接口

實現(xiàn)CommandLineRunner接口 然后在run方法里面調用需要調用的方法即可,好處是方法執(zhí)行時,項目已經初始化完畢,是可以正常提供服務的。

同時該方法也可以接受參數(shù),可以根據項目啟動時: java -jar demo.jar arg1 arg2 arg3 傳入的參數(shù)進行一些處理。

@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println(Arrays.toString(args));
    }
}

三、實現(xiàn)ApplicationRunner接口

實現(xiàn)ApplicationRunner接口和實現(xiàn)CommandLineRunner接口基本是一樣的。

唯一的不同是啟動時傳參的格式,CommandLineRunner對于參數(shù)格式沒有任何限制,ApplicationRunner接口參數(shù)格式必須是:–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());
        }
    }
}

四、實現(xiàn)ApplicationListener

實現(xiàn)接口ApplicationListener方式和實現(xiàn)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í)行”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI