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,作用於方法上面。