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。

 

也可以使用 @Order(value = 1)指定運行的順序。












1.使用 @PostConstruct,作用於方法上面。


免責聲明!

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



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