SpringBoot之ApplicationRunner

我們在開發中可能會需要在容器啓動的時候執行一些內容。比如讀取配置文件,加載路由信息,數據庫連接之類的。SpringBoot給我們提供了兩個接口來幫助我們實現這種需求。這兩個接口分別爲CommandLineRunner和ApplicationRunner。他們的執行時機爲容器啓動完成的時候。

ApplicationRunner源碼如下:

@FunctionalInterface
public interface ApplicationRunner {
    void run(ApplicationArguments args) throws Exception;
}

這個接口中有個run()方法,我們重寫這個方法即可,可以初始化一些路由信息等:

package com.daling.vendor.api.gateway;

import com.daling.vendor.api.gateway.configuration.RedisConfigChangeProcessor;
import com.daling.vendor.api.gateway.service.RouteManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class InitRoute implements ApplicationRunner{
    @Autowired
    private RouteManageService routeService;
 
    @Override
    public void run(ApplicationArguments args) throws Exception {
        routeService.init();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章