溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

springboot項目啟動后的執行方法有哪些

發布時間:2022-06-16 13:44:19 來源:億速云 閱讀:298 作者:iii 欄目:開發技術

今天小編給大家分享一下springboot項目啟動后的執行方法有哪些的相關知識點,內容詳細,邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

1 方法

  • ApplicationListener< ContextRefreshedEvent> 不推薦

  • ApplicationListener  推薦

  • CommandLineRunner 推薦

方法1:spring的ApplicationListener< ContextRefreshedEvent>接口

實現ApplicationListener接口,并實現 onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent)方法

@Service
public class SearchReceive implements  ApplicationListener<ContextRefreshedEvent> {
   @Override
   public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
       if (contextRefreshedEvent.getApplicationContext().getParent() == null) {//保證只執行一次
           //需要執行的方法
       }
   }
}

方法2:springboot的ApplicationRunner接口

ApplicationListener和CommandLineRunner兩個接口是springBoot提供用來在spring容器加載完成后執行指定方法。兩個接口區別主要是入參不同。

實現ApplicationRunner接口

@Component
@Order(value = 1)
public class AfterRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("執行方法");
    }
}

方法3:springboot的CommandLineRunner接口

實現CommandLineRunner接口

@Component
@Order(value = 2)
public class CommandLineRunnerImpl implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("執行方法");
    }
}

注:如果同時implements   ApplicationListener和CommandLineRunner兩個接口,ApplicationRunner接口的方法先執行,CommandLineRunner后執行;

@Slf4j
@Component
public class RunnerTest implements ApplicationRunner, CommandLineRunner {
 
  @Override
  public void run(ApplicationArguments args) throws Exception {
    System.out.println("服務啟動RunnerTest   ApplicationRunner執行啟動加載任務...");
  }
 
  @Override
  public void run(String... args) throws Exception {
    System.out.println("服務啟動RunnerTest    CommandLineRunner 執行啟動加載任務...");
    }
  }
}

2 指定執行順序

當項目中同時實現了ApplicationRunner和CommondLineRunner接口時,可使用Order注解或實現Ordered接口來指定執行順序,值越小越先執行。

3 原理

SpringApplication 的run方法會執行afterRefresh方法。

afterRefresh方法會執行callRunners方法。

callRunners方法會調用所有實現ApplicationRunner和CommondLineRunner接口的方法。

以上就是“springboot項目啟動后的執行方法有哪些”這篇文章的所有內容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學習更多的知識,請關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女