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 <<<<<<<<<<<<<

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值