springboot項目啟動之后初始化自定義配置類


前言

今天在寫項目的時候,需要再springboot項目啟動之后,加載我自定義的配置類的一些方法,百度了之后特此記錄下。

正文

方法有兩種:

1、 創建自定義類實現 CommandLineRunner接口,重寫run()方法。springboot啟動之后會默認去掃描所有實現了CommandLineRunner的類,並運行其run()方法。

@Component
@Order(2)   //通過order值的大小來決定啟動的順序
public class AskForLeave implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        askForLeave();
    }

    public void askForLeave(){
        System.out.println("項目啟動了,執行了方法");
    }
}

運行結果:

 

 2、創建自定義類實現ApplicationRunner 接口,重寫run()方法。

@Component
@Order(3)
public class Hello implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {

        hello();
    }

    public void hello(){
        System.out.println("項目又啟動了,這次使用的是:繼承 ApplicationRunner");
    }
}

結果如下:

關於二者的區別:

其實並沒有什么區別,如果想獲取更加詳細的參數的時候,可以選擇使用ApplicationRunner接口。其參數類型為:ApplicationArguments 。


免責聲明!

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



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