背景:有時候,在實際項目需求中可能需要在spring-boot啓動時,需要加載一些數據獲取運行某些方法,爲此,spring-boot提供了一寫方法;
第一種情況:spring-boot啓動時只需要加載少寫方法或者數據,實現方式是:
自定義一個類,然後讓該類去實現一個CommandlineRunner接口,並且去實現該接口中的run方法,將要預執行的數據或者預加載的方法可以放在其中;
@Component
public class StartLoad implements CommandLineRunner{
@Override
public void run(String... arg0) throws Exception {
System.out.println("在服務啓動時進行加載相應數據");
}
}
第二種情況:spring-boot啓動時需要加載多個方法,並且多個方法之間有先後順序的處理方式:
要加載的方法一:
@Component
@Order(“1”)
public class StartLoad implements CommandLineRunner{
@Override
public void run(String... arg0) throws Exception {
System.out.println("在服務啓動時進行加載的方法一");
}
}
要加載的方法二:
@Component
@Order(“1”)
public class StartLoad implements CommandLineRunner{
@Override
public void run(String... arg0) throws Exception {
System.out.println("在服務啓動時進行加載的方法一");
}
}