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的初始化工作。