SpringBoot應用在服務啟動后進行一些初始化工作


在一些場景中,當SpringBoot項目啟動后,我們可能會需要做一些寫入緩存或者初始常量信息等的初始化工作,此時便需要使用SpringBoot提供的Runner來實現。

SpringBoot實際上給我們提供了兩種在應用啟動后立即執行某些方法的方式,它們分別是【ApplicationRunner】和CommandLineRunner】。兩者的相同的在於它們都是在SpringApplication執行之后開始執行的,而不同點則在於CommandLineRunner接口提供的方法只能傳遞字符串,而ApplicationRunner是使用ApplicationArguments用來接收參數的,因此這個方式可以在更加復雜的場景中使用。

通過實現CommandLineRunner接口來實現啟動后執行特定邏輯

@Component
public class InitRunner implements CommandLineRunner {
    /**
     * 在服務啟動完成(特指SpringApplication)后立即執行
     */
    @Override
    public void run(String... args) throws Exception {
        System.out.println("This will be executed when the project is started!");
    }
}

 通過實現ApplicationRunner接口來實現啟動后執行特定邏輯

@Component
public class InitRunner implements ApplicationRunner {
    /**
     * 在服務啟動完成(特指SpringApplication)后立即執行
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
       System.out.println("This will be executed when the project is started!");
    }
}

這兩種方式的實現都很簡單,直接實現了相應的接口就可以了,但別忘了要在類上加上@Component注解。

注冊多個實現並指定初始化工作的優先級

如果想要將多個初始化工作拆分開的話,只要生成多個實現類即可。

另外如果想要指定啟動方法執行的順序的話,則可以通過實現【org.springframework.core.Ordered】接口或者使用【org.springframework.core.annotation.Order】注解來實現目的。

@Component
@Order(value = 1) 
public class InitRunner1 implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {       
        System.out.println("i like yanggb!");
    }    
}
@Component
@Order(value = 2) 
public class InitRunner2 implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {       
        System.out.println("i like yanggb too!");
    }    
}

在@Order注解中指定的value值越小,則執行的優先級越高,比如在上面的代碼中就會先打印出【i like yanggb!】,然后再打印出【i like yanggb too!】。

 

"所有不合時宜的相遇都是遺憾。"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM