在Spring boot项目的实际开发中,我们有时需要项目服务启动时加载一些数据或预先完成某些动作。为了解决这样的问题,Spring boot 为我们提供了一个方法:通过实现接口 CommandLineRunner 来实现这样的需求。

实现方式:只需要一个类即可,无需其他配置。

实现步骤:

1.创建实现接口 CommandLineRunner 的类 MyStartupRunnerTest

  1. package com.energy;
  2. import org.springframework.boot.CommandLineRunner;
  3. import org.springframework.core.annotation.Order;
  4. import org.springframework.stereotype.Component;
  5. /**
  6. * Created by CavanLiu on 2017/2/28 0028.
  7. */
  8. @Component
  9. @Order(value=1)
  10. public class MyStartupRunnerTest implements CommandLineRunner
  11. {
  12. @Override
  13. public void run(String... args) throws Exception
  14. {
  15. System.out.println(">>>>This is MyStartupRunnerTest Order=1. Only testing CommandLineRunner...<<<<");
  16. }
  17. }

2.创建实现接口CommandLineRunner 的类 MyStartupRunnerTest2

  1. package com.energy;
  2. import org.springframework.boot.CommandLineRunner;
  3. import org.springframework.core.annotation.Order;
  4. import org.springframework.stereotype.Component;
  5. /**
  6. * Created by CavanLiu on 2017/2/28 0028.
  7. */
  8. @Component
  9. @Order(value=2)
  10. public class MyStartupRunnerTest2 implements CommandLineRunner
  11. {
  12. @Override
  13. public void run(String... args) throws Exception
  14. {
  15. System.out.println(">>>>This is MyStartupRunnerTest Order=2. Only testing CommandLineRunner...<<<<");
  16. }
  17. }

3.启动Spring boot后查看控制台输出信息,如下所示:

  1. >>>>This is MyStartupRunnerTest Order=1. Only testing CommandLineRunner...<<<<
  2. >>>>This is MyStartupRunnerTest2 Order=2. Only testing CommandLineRunner...<<<<

4.Application启动类代码略。

说明:CommandLineRunner接口的运行顺序是依据@Order注解的value由小到大执行,即value值越小优先级越高。

最新文章

  1. 【JavaWeb】Spring+SpringMVC+MyBatis+SpringSecurity+EhCache+JCaptcha 完整Web基础框架(一)
  2. Divide Two Integers
  3. POJ1014Dividing(DP)
  4. transfrom属性
  5. UIPageControll - 图片格式
  6. SCGHR 系统设计
  7. css ie hack整理
  8. proxy 利用get拦截,实现一个生成各种DOM节点的通用函数dom。
  9. IT学习方法
  10. ntp服务器池列表
  11. 深信服笔试题(网络project师售后)
  12. boost::thread类
  13. java之反射
  14. keepalived给LVS带来了什么
  15. zookeeper客户端 zkCli使用及常用命令
  16. Luogu P3455 [POI2007]ZAP-Queries
  17. STM32串口打印输出乱码的解决办法
  18. zoj1716简单的二维树状数组
  19. vscode使用wsl调试代码
  20. rabbitMQ概念详细介绍

热门文章

  1. 【LOJ】#2244. 「NOI2014」起床困难综合症
  2. Django实战(3):Django也可以有scaffold
  3. servlet文件下载实例剖析
  4. react篇章-React State(状态)-组件都是真正隔离的
  5. ASL测试 课题测试博客
  6. The file will have its original line endings in your working directory.
  7. CSUOJ 1868 潜在好友
  8. 【原创】SQL Server常用脚本整理
  9. Android自动化页面测速在美团的实践
  10. spring 装配bean的三种方式