Java項目啟動時執行指定方法的幾種方式


1.使用 @PostConstruct,作用於方法上面:類加載后執行,不依賴於項目的啟動,經常可以看到項目未啟動成功該方法就已經執行了

@Component
public class PostConstruct {

@PostConstruct
public void test() {
System.out.println("PostConstruct:開始運行...");
}
}

2.使用 CommandLineRunner 接口:在服務啟動后執行

@Component
public class Start implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner:開始運行...");
}
}

3.使用 ApplicationRunner 接口

@Component
public class Start1 implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner:開始運行...");
}
}

以上三種方式都是在項目啟動的時候加載指定的方法,第一種使用的是 注解的方式,第二種、第三種使用的是實現接口的方式。

它們的執行順訊為 @PostConstruct---》ApplicationRunner---》CommandLineRunner。

CommandLineRunner 和ApplicationRunner 的作用都是用於項目啟動后進行數據的初始化。如有多個Runner的話,可以使用 @Order(value = 1)指定運行的順序。 數字越小越早運行。

@PostConstruct:在Spring實例化該Bean之后馬上執行此方法,之后才會去實例化其他Bean

 


免責聲明!

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



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