SpringBoot入門十一,啓動後自動執行指定代碼

Springboot設置啓動後自動執行指定代碼,可以調用這兩個接口:
  ApplicationRunner
  CommandLineRunner
他們的執行時機爲容器啓動完成的時候,這裏使用ApplicationRunner來實現需要的效果,直接上代碼:

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(1)   // 如果有多個類實現了ApplicationRunner接口,可以使用此註解指定執行順序
public class SysEhcacheInit implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("SysEhcacheInit執行時啓動了~~");
    }
}

注意:代碼中的@Order代表執行優先級,越小優先級越高
效果如下:
SpringBoot入門十一,啓動後自動執行指定代碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章