博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot之CommandLineRunner接口和ApplicationRunner接口
阅读量:2394 次
发布时间:2019-05-10

本文共 1465 字,大约阅读时间需要 4 分钟。

我们在开发中可能会有这样的情景。需要在容器启动的时候执行一些内容。比如读取配置文件,数据库连接之类的。SpringBoot给我们提供了两个接口来帮助我们实现这种需求。这两个接口分别为CommandLineRunner和ApplicationRunner。他们的执行时机为容器启动完成的时候。

这两个接口中有一个run方法,我们只需要实现这个方法即可。这两个接口的不同之处在于:ApplicationRunner中run方法的参数为ApplicationArguments,而CommandLineRunner接口中run方法的参数为String数组。下面我写两个简单的例子,来看一下这两个接口的实现。

CommandLineRunner

具体代码如下:
[java]   
  1. package com.zkn.learnspringboot.runner;  
  2.   
  3. import org.springframework.boot.CommandLineRunner;  
  4. import org.springframework.stereotype.Component;  
  5.   
  6. /** 
  7.  * Created by zkn on 2016/8/12. 
  8.  */  
  9. @Component  
  10. public class TestImplCommandLineRunner implements CommandLineRunner {  
  11.   
  12.   
  13.     @Override  
  14.     public void run(String... args) throws Exception {  
  15.   
  16.         System.out.println("<<<<<<<<<<<<这个是测试CommandLineRunn接口>>>>>>>>>>>>>>");  
  17.     }  
  18. }  
执行结果为:

ApplicationRunner接口

具体代码如下:
[java]   
  1. package com.zkn.learnspringboot.runner;  
  2.   
  3. import org.springframework.boot.ApplicationArguments;  
  4. import org.springframework.boot.ApplicationRunner;  
  5. import org.springframework.stereotype.Component;  
  6.   
  7. /** 
  8.  * Created by zkn on 2016/8/12. 
  9.  * 注意:一定要有@Component这个注解。要不然SpringBoot扫描不到这个类,是不会执行。 
  10.  */  
  11. @Component  
  12. public class TestImplApplicationRunner implements ApplicationRunner {  
  13.   
  14.   
  15.     @Override  
  16.     public void run(ApplicationArguments args) throws Exception {  
  17.         System.out.println(args);  
  18.         System.out.println("这个是测试ApplicationRunner接口");  
  19.     }  
  20. }  
执行结果如下:

@Order注解

如果有多个实现类,而你需要他们按一定顺序执行的话,可以在实现类上加上@Order注解。@Order(value=整数值)。SpringBoot会按照@Order中的value值从小到大依次执行。

Tips

如果你发现你的实现类没有按照你的需求执行,请看一下实现类上是否添加了Spring管理的注解(@Component)。
你可能感兴趣的文章
Connecting to GPRS over Bluetooth on Linux
查看>>
Linux网络资源
查看>>
Android对Kernel的改动汇总
查看>>
WGET 通过代理下载
查看>>
JITTER BUFFER
查看>>
IP协议报头学习笔记
查看>>
关于SIGPIPE导致的程序退出
查看>>
基于MTD的NAND驱动开发
查看>>
linux mtd源码分析(好东西)
查看>>
关于SIGBUS的总结
查看>>
JSP--9大隐式对象
查看>>
Servelt中主要对象的使用
查看>>
EL表达式的深刻认识
查看>>
JSP技术的学习总结
查看>>
JavaBean的初步认知
查看>>
重识java反射
查看>>
Spring的核心中IOC、DI
查看>>
Spring中注解的使用
查看>>
Spring的认识
查看>>
maven项目出现如下错误,求指点;CoreException: Could not calculate build plan:
查看>>