CommandLineRunner、ApplicationRunner 接口
生活随笔
收集整理的這篇文章主要介紹了
CommandLineRunner、ApplicationRunner 接口
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? ? ?如果我們想在項目啟動后做一些事情(如加載定時任務,初始化工作),可以使用spring提供的CommandLineRunner、ApplicationRunner 接口,在容器啟動成功后的最后一步回調(類似開機自啟動)。
1. CommandLineRunner接口
/*** Interface used to indicate that a bean should <em>run</em> when it is contained within* a {@link SpringApplication}. Multiple {@link CommandLineRunner} beans can be defined* within the same application context and can be ordered using the {@link Ordered}* interface or {@link Order @Order} annotation.* <p>* If you need access to {@link ApplicationArguments} instead of the raw String array* consider using {@link ApplicationRunner}.** @author Dave Syer* @see ApplicationRunner*/ public interface CommandLineRunner {/*** Callback used to run the bean.* @param args incoming main method arguments* @throws Exception on error*/void run(String... args) throws Exception;}多個CommandLineRunner可以被同時執行在同一個spring上下文中并且執行順序是以order注解的參數順序一致。
下面看一個demo:
@Order(2) @Component public class ServerStartedReport implements CommandLineRunner{@Overridepublic void run(String... args) throws Exception {System.out.println("===========ServerStartedReport啟動====="+ LocalDateTime.now());} }配置參數啟動項目:
控制臺打印:
2. ApplicationRunner接口
? ? ? ?二者基本一樣,區別在于接收的參數不一樣。CommandLineRunner的參數是最原始的參數,沒有做任何處理,而ApplicationRunner的參數是ApplicationArguments,對原始參數做了進一步的封裝。
如我們在這里配置了一些啟動參數--foo=hu --log=debug
CommandLineRunner只是獲取--name=value。而ApplicationRunner可以解析--name=value,使得我們可以直接通過name來獲取value。
打印結果為:
===========ServerStartedReport啟動=====2019-02-14T21:36:23.668 ApplicationRunner:[--foo=hu, --log=debug] getOptionNames:[log, foo] getOptionValues:[hu] getOptionValues:[debug]注意啟動后執行的方法一定要加try catch,因為此處拋出異常會影響項目啟動。
總結
以上是生活随笔為你收集整理的CommandLineRunner、ApplicationRunner 接口的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mybatis的如何根据下划线_,百分号
- 下一篇: 从@Transactional看事务的传