springboot之启动加载数据 CommandLineRunner 和ApplicationRunner
Spring Boot 启动加载数据 CommandLineRunner 和ApplicationRunner 在实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求。 为了解决这样的问题,springboot为我们提供了一个方法,通过实现接口 CommandLineRunner 和ApplicationRunner来实现。 Springboot应用程序在启动后,会遍历CommandLineRunner接口的实例并运行它们的run方法。也可以利用@Order注解(或者实现Order接口)来规定所有CommandLineRunner实例的运行顺序。 根据控制台结果可判断,@Order 注解的执行优先级是按value值从小到大顺序。
本例将采用maven管理,代码托管在github上,地址:https://github.com/wolf909867753/springboot。
1。创建maven-module,runnerDesc,并在pom.xml中添加springboot依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <artifactId>runnerDesc</artifactId> <packaging>war</packaging> <name>springboot-runnerDesc (CommandLineRunner and ApplicationRunner)Demo</name> <url>http://maven.apache.org</url> <!-- Spring Boot 启动父依赖 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.1.RELEASE</version> </parent> <dependencies> <!-- Spring Boot Web 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>runnerDesc</finalName> </build> </project>
2.工程目录如下:
@Component @Order(value = 1)//优先级 public class TestImplApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments applicationArguments) throws Exception { System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 11111111 <<<<<<<<<<<<<"); } }
@Component @Order(value = 2)//优先级 public class TestImplCommandLineRunner implements CommandLineRunner { @Override public void run(String... strings) throws Exception { System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 22222222 <<<<<<<<<<<<<"); } public static void main(String[] args) { SpringApplication.run(TestImplCommandLineRunner.class,args); } }
3.编译代码并添加到tomcat或者jetty运行
>>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 11111111 <<<<<<<<<<<<<
>>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 22222222 <<<<<<<<<<<<<