1. 程式人生 > >Springboot2.x初始化 專案資料

Springboot2.x初始化 專案資料

Springboot2.x 初始化專案資料

1.初始化類
  • CommandLineRunner 介面的 Component 會在所有 Spring Beans 都初始化之後,SpringApplication.run() 之前執行,非常適合在應用程式啟動之初進行一些資料初始化的工作
@Component
public class MyRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("在SpringApplication.run() 之前執行");
    }
}
2.在啟動類上新增驗證啟動順序
  • 在main方法裡操作(不建議)
@SpringBootApplication
public class SpringApplication {

    public static void main(String[] args) {
        System.out.println("執行run之前");
        SpringApplication.run(SpringApplication.class, args);
        System.out.println("執行run之後");
    }
}
3.使用註解 @PostConstruct 和 @PreDestroy
  • @PostConstruct修飾的方法會在伺服器載入Servle的時候執行,並且只會被伺服器執行一次。
  • PostConstruct在建構函式之後執行,init()方法之前執行。
  • PreDestroy()方法在destroy()方法執行執行之後執行
 /**
     * @ PostConstruct修飾的方法會在伺服器載入Servle的時候執行,
     * 並且只會被伺服器執行一次。
     * PostConstruct在建構函式之後執行,init()方法之前執行。
     */
    @PostConstruct
    public void initializeUpdateExchangeRate() {
        updateExchangeRate();
    }