javascript
SpringBoot配置在应用启动后立即执行某些方法代码案例
springboot給我們提供了兩種“開機(jī)啟動(dòng)”方式:ApplicationRunner和CommandLineRunner。
這兩種方法提供的目的是為了滿足,在項(xiàng)目啟動(dòng)的時(shí)候立刻執(zhí)行某些方法。我們可以通過實(shí)現(xiàn)ApplicationRunner和CommandLineRunner,來實(shí)現(xiàn),他們都是在SpringApplication 執(zhí)行之后開始執(zhí)行的。
CommandLineRunner接口可以用來接收字符串?dāng)?shù)組的命令行參數(shù),ApplicationRunner 是使用ApplicationArguments 用來接收參數(shù)的。
CommandLineRunner :
@Component public class MyCommandLineRunner implements CommandLineRunner{@Overridepublic void run(String... var1) throws Exception{System.out.println("This will be execute when the project was started!");} }ApplicationRunner :
@Component public class MyApplicationRunner implements ApplicationRunner {@Overridepublic void run(ApplicationArguments var1) throws Exception{System.out.println("MyApplicationRunner class will be execute when the project was started!");} }這兩種方式的實(shí)現(xiàn)都很簡(jiǎn)單,直接實(shí)現(xiàn)了相應(yīng)的接口就可以了。
記得在類上加@Component注解。
如果想要指定啟動(dòng)方法執(zhí)行的順序,可以通過實(shí)現(xiàn)org.springframework.core.Ordered接口或者使用org.springframework.core.annotation.Order注解來實(shí)現(xiàn)。
以ApplicationRunner 為例來分別實(shí)現(xiàn)。
Ordered接口:
@Component public class MyApplicationRunner implements ApplicationRunner,Ordered{@Overridepublic int getOrder(){return 1;//通過設(shè)置這里的數(shù)字來知道指定順序}@Overridepublic void run(ApplicationArguments var1) throws Exception{System.out.println("MyApplicationRunner1!");} }Order注解實(shí)現(xiàn)方式:
@Component @Order(value = 1) public class MyApplicationRunner implements ApplicationRunner{@Overridepublic void run(ApplicationArguments var1) throws Exception{System.out.println("MyApplicationRunner1!");}} 與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的SpringBoot配置在应用启动后立即执行某些方法代码案例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: redis在实际项目中使用实例
- 下一篇: 远程桌面上的文件复制到本地