在我们实际工作中,总会遇到这样需求,在项目启动的时候需要做一些初始化的操作,比如初始化线程池,提前加载好加密证书等。今天就给大家介绍一个 Spring Boot 神器,专门帮助大家解决项目启动初始化资源操作。

这个神器就是 CommandLineRunnerCommandLineRunner 接口的 Component 会在所有 Spring Beans都初始化之后,SpringApplication.run()之前执行,非常适合在应用程序启动之初进行一些数据初始化的工作。

接下来我们就运用案例测试它如何使用,在测试之前在启动类加两行打印提示,方便我们识别 CommandLineRunner 的执行时机。

@SpringBootApplication
public class CommandLineRunnerApplication {public static void main(String[] args) {System.out.println("The service to start.");SpringApplication.run(CommandLineRunnerApplication.class, args);System.out.println("The service has started.");}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

接下来我们直接创建一个类继承 CommandLineRunner ,并实现它的 run() 方法。

@Component
public class Runner implements CommandLineRunner {@Overridepublic void run(String... args) throws Exception {System.out.println("The Runner start to initialize ...");}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

我们在 run() 方法中打印了一些参数来看出它的执行时机。完成之后启动项目进行测试:

...
The service to start..   ____          _            __ _ _/\\ / ___'_ __ _ _(_)_ __  __ _ \\\\( ( )\___ | '_ | '_| | '_ \/ _` | \\\\ \\/  ___)| |_)| | | | | || (_| |  ) ) ) )'  |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot ::        (v2.0.0.RELEASE)
...
2018-04-21 22:21:34.706  INFO 27016 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-04-21 22:21:34.710  INFO 27016 --- [           main] com.neo.CommandLineRunnerApplication     : Started CommandLineRunnerApplication in 3.796 seconds (JVM running for 5.128)
The Runner start to initialize ...
The service has started.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

根据控制台的打印信息我们可以看出 CommandLineRunner 中的方法会在 Spring Boot 容器加载之后执行,执行完成后项目启动完成。

如果我们在启动容器的时候需要初始化很多资源,并且初始化资源相互之间有序,那如何保证不同的 CommandLineRunner的执行顺序呢?Spring Boot 也给出了解决方案。那就是使用 @Order 注解。

我们创建两个 CommandLineRunner 的实现类来进行测试:

第一个实现类:

@Component
@Order(1)
public class OrderRunner1 implements CommandLineRunner {@Overridepublic void run(String... args) throws Exception {System.out.println("The OrderRunner1 start to initialize ...");}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

第二个实现类:

@Component
@Order(2)
public class OrderRunner2 implements CommandLineRunner {@Overridepublic void run(String... args) throws Exception {System.out.println("The OrderRunner2 start to initialize ...");}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

添加完成之后重新启动,观察执行顺序:

...
The service to start..   ____          _            __ _ _/\\ / ___'_ __ _ _(_)_ __  __ _ \\\\( ( )\___ | '_ | '_| | '_ \/ _` | \\\\ \\/  ___)| |_)| | | | | || (_| |  ) ) ) )'  |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot ::        (v2.0.0.RELEASE)
...
2018-04-21 22:21:34.706  INFO 27016 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-04-21 22:21:34.710  INFO 27016 --- [           main] com.neo.CommandLineRunnerApplication     : Started CommandLineRunnerApplication in 3.796 seconds (JVM running for 5.128)
The OrderRunner1 start to initialize ...
The OrderRunner2 start to initialize ...
The Runner start to initialize ...
The service has started.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

通过控制台的输出我们发现,添加 @Order 注解的实现类最先执行,并且@Order()里面的值越小启动越早。

在实践中,使用ApplicationRunner也可以达到相同的目的,两着差别不大。看来使用 Spring Boot 解决初始化资源的问题非常简单。

示例代码-github

示例代码-码云

Spring Boot 2.0(七):Spring Boot 如何解决项目启动时初始化资源相关推荐

  1. Spring Boot 2 (七):Spring Boot 如何解决项目启动时初始化资源

    Spring Boot 2 (七):Spring Boot 如何解决项目启动时初始化资源 在项目启动的时候需要做一些初始化的操作,比如初始化线程池,提前加载好加密证书等.今天就给大家介绍一个 Spri ...

  2. (转)Spring Boot 2 (七):Spring Boot 如何解决项目启动时初始化资源

    http://www.ityouknow.com/springboot/2018/05/03/spring-boot-commandLineRunner.html 在我们实际工作中,总会遇到这样需求, ...

  3. java 项目启动初始化_Spring Boot解决项目启动时初始化资源的方法

    前言 在我们实际工作中,总会遇到这样需求,在项目启动的时候需要做一些初始化的操作,比如初始化线程池,提前加载好加密证书等.今天就给大家介绍一个 Spring Boot 神器,专门帮助大家解决项目启动初 ...

  4. Spring Boot 5:应用程序启动时初始化资源

    需求:应用程序启动后,初始化基础数据.加密证书等操作. 可以使用CommandLineRunner接口来实现,在SpringBoot.run()之后完成资源的初始化工作. 注意:多个Runner需要顺 ...

  5. InfoQ就Spring Boot 2.0 GA版发布采访了项目牵头人Phil Webb

    \ 看新闻很累?看技术新闻更累?试试下载InfoQ手机客户端,每天上下班路上听新闻,有趣还有料! \ \\ 广受期待的Spring Boot 2.0近期由Spring的托管企业Pivotal发布.这是 ...

  6. Spring Boot 2.0 利用 Spring Security 实现简单的OAuth2.0认证方式1

    0. 前言 之前帐号认证用过自己写的进行匹配,现在要学会使用标准了.准备了解和使用这个OAuth2.0协议. 1. 配置 1.1 配置pom.xml 有些可能会用不到,我把我项目中用到的所有包都贴出来 ...

  7. Spring Boot 2.0 with Spring 5 Kotlin support and Spring WebFlux functional

    Spring Boot 2.0 with Spring 5 Kotlin support and Spring WebFlux functional

  8. 项目启动时socket自动启动_spring boot 项目在启动时调用接口

    1.环境 目前开发的项目使用的spring boot(2.1.4.RELEASE)+ssm 2. 需求 现在有一个数据处理任务的接口,在spring boot项目启动后,可以手动的去启动任务,但是这样 ...

  9. spring定时任务需要在项目启动时执行一次

    spring定时任务需要在项目启动时执行一次,然后再按照指定规则执行 在定时任务方法上加注解@PostConstruct,不是spring提供的注解,是JAVA原生注解,在初始化servlet之前执行 ...

最新文章

  1. DIV+CSS规范命名大全集合
  2. python输出到语音播放_用Python写一个语音播放软件
  3. matlab工作路径
  4. 卸载源码安装mysql_CentOS 7.x 卸载删除MariaDB,重新安装,安装MYSQL离线版和源代码...
  5. ORA-00031: session marked for kill 标记要终止的会话
  6. jQuery如何在线导入js包
  7. nodejs mysql事务处理_关于NodeJs如何使用Mysql模块实现事务处理实例
  8. 架构应用之高可用、高复用
  9. 又要头秃?2020 年七大 AI 编程语言大盘点
  10. RDLC之自定義數據集二
  11. RadASM DosBox设置无法生效问题
  12. Practicing Programming
  13. 树莓派4B中中文字体和中文输入法设置不成功问题解决办法
  14. 新个税来了!一图看清你能省多少钱,转需! ​​​​
  15. git设置用户名密码
  16. 再见,Python正则表达式!
  17. 全国计算机三级网络技术电子版,全国计算机三级网络技术最新版笔试电子教材(完全免费版).doc...
  18. Microsoft Security Essentials Beta 出自微软的单机版缉毒尖兵
  19. 教师工作量计算系统 课程设计 C语言
  20. IdentityServer4 DiscoveryClient找不到

热门文章

  1. 深入理解多线程(一)——Synchronized的实现原理
  2. Matlab画图,去掉周围白边
  3. 破译手势在对话中的意义
  4. 程序员面试题精选100题(16)-O(logn)求Fibonacci数列[算法]
  5. Coursera课程Python for everyone:chapter 2
  6. 局部特征(5)——如何利用彩色信息 Color Descriptors
  7. Day 13: Dropwizard —— 非常棒的Java REST服务器栈
  8. 几个机器学习算法及应用领域相关的中国大牛
  9. 数据处理踩过的坑(不断更新):
  10. Golang基础之数组