Spring Boot中初始化資源的幾種方式


CommandLineRunner

  • 定義初始化類 MyCommandLineRunner
  • 實現 CommandLineRunner接口,並實現它的 run()方法,在該方法中編寫初始化邏輯
  • 注冊成Bean,添加 @Component注解即可
  • 示例代碼如下:
@Component public class MyCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("...init resources by implements CommandLineRunner"); } } 

  實現了 CommandLineRunner 接口的 Component 會在所有 Spring Beans 初始化完成之后在 SpringApplication.run() 執行之前完成。下面通過加兩行打印來驗證我們的測試。




ApplicationRunner

  • 定義初始化類 MyApplicationRunner
  • 實現 ApplicationRunner接口,並實現它的 run()方法,在該方法中編寫初始化邏輯
  • 注冊成Bean,添加 @Component注解即可
  • 示例代碼如下:
@Component public class MyApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments applicationArguments) throws Exception { System.out.println("...init resources by implements ApplicationRunner"); } } 

  可以看到,通過實現 ApplicationRunner 接口,和通過實現 CommandLineRunner 接口都可以完成項目的初始化操作,實現相同的效果。兩者之間唯一的區別是 run()方法中自帶的形參不相同,在 CommandLineRunner 中只是簡單的String... args形參,而 ApplicationRunner 則是包含了 ApplicationArguments 對象,可以幫助獲得更豐富的項目信息。




 

@PostConstruct 

 

使用 @PostConstruct 注解同樣可以幫助我們完成資源的初始化操作,前提是這些初始化操作不需要依賴於其它Spring beans的初始化工作。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM