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

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

@Component
public class PostConstruct {

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

2.使用 ApplicationRunner。spa

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

3.使用 CommandLineRunner 接口接口

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

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

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

 

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

1.使用 @PostConstruct,做用於方法上面。
相關文章
相關標籤/搜索