CommandLineRunner、ApplicationRunner 接口
? ? ? ?如果我們想在項(xiàng)目啟動(dòng)后做一些事情(如加載定時(shí)任務(wù),初始化工作),可以使用spring提供的CommandLineRunner、ApplicationRunner 接口,在容器啟動(dòng)成功后的最后一步回調(diào)(類(lèi)似開(kāi)機(jī)自啟動(dòng))。
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;}多個(gè)CommandLineRunner可以被同時(shí)執(zhí)行在同一個(gè)spring上下文中并且執(zhí)行順序是以order注解的參數(shù)順序一致。
下面看一個(gè)demo:
@Order(2) @Component public class ServerStartedReport implements CommandLineRunner{@Overridepublic void run(String... args) throws Exception {System.out.println("===========ServerStartedReport啟動(dòng)====="+ LocalDateTime.now());} }配置參數(shù)啟動(dòng)項(xiàng)目:
控制臺(tái)打印:
2. ApplicationRunner接口
? ? ? ?二者基本一樣,區(qū)別在于接收的參數(shù)不一樣。CommandLineRunner的參數(shù)是最原始的參數(shù),沒(méi)有做任何處理,而ApplicationRunner的參數(shù)是ApplicationArguments,對(duì)原始參數(shù)做了進(jìn)一步的封裝。
如我們?cè)谶@里配置了一些啟動(dòng)參數(shù)--foo=hu --log=debug
CommandLineRunner只是獲取--name=value。而ApplicationRunner可以解析--name=value,使得我們可以直接通過(guò)name來(lái)獲取value。
打印結(jié)果為:
===========ServerStartedReport啟動(dòng)=====2019-02-14T21:36:23.668 ApplicationRunner:[--foo=hu, --log=debug] getOptionNames:[log, foo] getOptionValues:[hu] getOptionValues:[debug]注意啟動(dòng)后執(zhí)行的方法一定要加try catch,因?yàn)榇颂帓伋霎惓?huì)影響項(xiàng)目啟動(dòng)。
總結(jié)
以上是生活随笔為你收集整理的CommandLineRunner、ApplicationRunner 接口的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Mybatis的如何根据下划线_,百分号
- 下一篇: 从@Transactional看事务的传