spring boot启动加载数据原理分析
作者:牛头人 时间:2021-06-16 07:56:15
实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求。
为了解决这样的问题,spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来实现。
创建实现接口 CommandLineRunner 的类,通过@Component注解,就可以实现启动时加载数据项。使用@Order 注解来定义执行顺序。
IndexStartupRunner.Java类:
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 服务启动执行
*/
@Component
@Order(value=1)
public class IndexStartupRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("
IndexStartupRunner
>>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 <<<<<<<<<<<<<");
}
}
IndexStartupRunner2.java类:
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 服务启动执行
*/
@Component
@Order(value=2)
public class IndexStartupRunner2 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("
IndexStartupRunner2
>>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 <<<<<<<<<<<<<");
}
}
启动程序后,控制台输出结果为:
>>>>>>>>>>>>>>>IndexStartupRunner服务启动执行,执行加载数据等操作<<<<<<<<<<<<<
>>>>>>>>>>>>>>>IndexStartupRunner2服务启动执行,执行加载数据等操作<<<<<<<<<<<<<
根据控制台结果可判断,@Order 注解的执行优先级是按value值从小到大顺序。
ComandLineRunner和ApplicationRunner区别和使用
如果需要在springapplication启动之后运行一些特定的代码,可以实现 ApplicationRunner 或
CommandLineRunner 接口。 两个接口以相同的方式工作,并提供了一个单一的 run 方法,该方法将被调用
SpringApplication.run(…) 完成之前。
这两个接口的不同之处在于:ApplicationRunner中run方法的参数为ApplicationArguments,而CommandLineRunner接口中run方法的参数为String数组。
以上所述是小编给大家介绍的spring boot启动加载数据原理分析网站的支持!
来源:http://www.cnblogs.com/web424/p/6755996.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
SpringBoot中的multipartResolver上传文件配置
C# 图片剪切与缩小的实例
解决FeignClient发送post请求异常的问题
Java服务限流算法的6种实现
![](https://img.aspxhome.com/file/2023/3/62993_0s.jpg)
java批量修改文件后缀名方法总结
![](https://img.aspxhome.com/file/2023/5/62655_0s.png)
JAVA ArrayList详细介绍(示例)
![](https://img.aspxhome.com/file/2023/3/61143_0s.jpg)
java和javascript中过滤掉img形式的字符串不显示图片的方法
![](https://img.aspxhome.com/file/2023/8/65738_0s.png)
JAVA面试题String产生了几个对象
![](https://img.aspxhome.com/file/2023/2/95462_0s.png)
通过实例解析Spring Ioc项目实现过程
![](https://img.aspxhome.com/file/2023/5/59745_0s.png)
java中如何获取相关参数
idea创建maven父子工程导致子工程无法导入父工程依赖
![](https://img.aspxhome.com/file/2023/0/87140_0s.png)
详解Docker学习笔记之搭建一个JAVA Tomcat运行环境
利用Distinct()内置方法对List集合的去重问题详解
.NET创建、删除、复制文件夹及其子文件的实例方法
C#数据结构之双向链表(DbLinkList)实例详解
![](https://img.aspxhome.com/file/2023/4/96384_0s.png)
Android语音识别技术详解及实例代码
![](https://img.aspxhome.com/file/2023/6/99796_0s.jpg)
Java多线程wait()和notify()方法详细图解
![](https://img.aspxhome.com/file/2023/1/66231_0s.png)
一步步教你如何创建第一个C#项目
![](https://img.aspxhome.com/file/2023/5/83295_0s.png)
Java实现英文猜词游戏的示例代码
![](https://img.aspxhome.com/file/2023/5/78295_0s.jpg)
Spring Cloud Eureka(全面解析) 大白话
![](https://img.aspxhome.com/file/2023/5/62735_0s.png)