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

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

CommandLineRunner

具体代码如下:

package com.zkn.learnspringboot.runner;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component; /**
* Created by zkn on 2016/8/12.
*/
@Component
public class TestImplCommandLineRunner implements CommandLineRunner { @Override
public void run(String... args) throws Exception { System.out.println("<<<<<<<<<<<<这个是测试CommandLineRunn接口>>>>>>>>>>>>>>");
}
}
执行结果为:

ApplicationRunner接口

具体代码如下:
package com.zkn.learnspringboot.runner;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component; /**
* Created by zkn on 2016/8/12.
* 注意:一定要有@Component这个注解。要不然SpringBoot扫描不到这个类,是不会执行。
*/
@Component
public class TestImplApplicationRunner implements ApplicationRunner { @Override
public void run(ApplicationArguments args) throws Exception {
System.out.println(args);
System.out.println("这个是测试ApplicationRunner接口");
}
}

执行结果如下:

@Order注解

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

Tips

如果你发现你的实现类没有按照你的需求执行,请看一下实现类上是否添加了Spring管理的注解(@Component)。

最新文章

  1. Android 的Parcelable接口
  2. Beginning Scala study note(1) Geting Started with Scala
  3. 0x80040E14 Caused by Max Url Length bug
  4. JavaScript老梗之this对象
  5. ORACLE 数据库 MOD 函数用法
  6. Core Foundation框架
  7. ThinkPHP提交表单判断上传图片经验总结
  8. [转]Not enough free disk space on disk &#39;/boot&#39;
  9. jacob如何获取word文档的页码
  10. 跨域名设置cookie或获取cookie
  11. OO之装饰者模式
  12. django ORM中update_or_create功能,如果只要匹配某一特定字段呢
  13. 个人Source Insight使用设置笔记
  14. [Swift]LeetCode911. 在线选举 | Online Election
  15. Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable) E: Unable to lock the administration di
  16. pycharm光标变成黑框,恢复成竖线
  17. C#写UTF8文件时指定是否含BOM头
  18. 第一部分 Mysql的基础
  19. 【转载】漫谈C++:良好的编程习惯与编程要点
  20. (转)将rdlc报表作为资源嵌套使用

热门文章

  1. Linux帮助——获取帮助
  2. Python【day 11】函数名的应用
  3. Vue内置组件[回顾]
  4. [b0013] Hadoop 版hello word mapreduce wordcount 运行(三)
  5. 微信支付:chooseWXPay:fail, the permission value is offline verifying
  6. Centos7 安装 zabbix 4.0
  7. Mysql优化之6年工作经验总结
  8. 如何在Etherscan.io 部署ETH以太坊智能合约 如何在15分钟内创建你的加密货币
  9. flask的request如何获取参数
  10. 交换机与MPLS