springboot 启动类CommandLineRunner(转载)
2024-08-30 23:00:25
在Spring boot项目的实际开发中,我们有时需要项目服务启动时加载一些数据或预先完成某些动作。为了解决这样的问题,Spring boot 为我们提供了一个方法:通过实现接口 CommandLineRunner 来实现这样的需求。
实现方式:只需要一个类即可,无需其他配置。
实现步骤:
1.创建实现接口 CommandLineRunner 的类 MyStartupRunnerTest
- package com.energy;
- import org.springframework.boot.CommandLineRunner;
- import org.springframework.core.annotation.Order;
- import org.springframework.stereotype.Component;
- /**
- * Created by CavanLiu on 2017/2/28 0028.
- */
- @Component
- @Order(value=1)
- public class MyStartupRunnerTest implements CommandLineRunner
- {
- @Override
- public void run(String... args) throws Exception
- {
- System.out.println(">>>>This is MyStartupRunnerTest Order=1. Only testing CommandLineRunner...<<<<");
- }
- }
2.创建实现接口CommandLineRunner 的类 MyStartupRunnerTest2
- package com.energy;
- import org.springframework.boot.CommandLineRunner;
- import org.springframework.core.annotation.Order;
- import org.springframework.stereotype.Component;
- /**
- * Created by CavanLiu on 2017/2/28 0028.
- */
- @Component
- @Order(value=2)
- public class MyStartupRunnerTest2 implements CommandLineRunner
- {
- @Override
- public void run(String... args) throws Exception
- {
- System.out.println(">>>>This is MyStartupRunnerTest Order=2. Only testing CommandLineRunner...<<<<");
- }
- }
3.启动Spring boot后查看控制台输出信息,如下所示:
- >>>>This is MyStartupRunnerTest Order=1. Only testing CommandLineRunner...<<<<
- >>>>This is MyStartupRunnerTest2 Order=2. Only testing CommandLineRunner...<<<<
4.Application启动类代码略。
说明:CommandLineRunner接口的运行顺序是依据@Order注解的value由小到大执行,即value值越小优先级越高。
最新文章
- 【JavaWeb】Spring+SpringMVC+MyBatis+SpringSecurity+EhCache+JCaptcha 完整Web基础框架(一)
- Divide Two Integers
- POJ1014Dividing(DP)
- transfrom属性
- UIPageControll - 图片格式
- SCGHR 系统设计
- css ie hack整理
- proxy 利用get拦截,实现一个生成各种DOM节点的通用函数dom。
- IT学习方法
- ntp服务器池列表
- 深信服笔试题(网络project师售后)
- boost::thread类
- java之反射
- keepalived给LVS带来了什么
- zookeeper客户端 zkCli使用及常用命令
- Luogu P3455 [POI2007]ZAP-Queries
- STM32串口打印输出乱码的解决办法
- zoj1716简单的二维树状数组
- vscode使用wsl调试代码
- rabbitMQ概念详细介绍