SpringBoot的ApplicationRunner与CommandLineRunner

导读:本篇文章讲解 SpringBoot的ApplicationRunner与CommandLineRunner,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

概述

开发中可能会有这样的场景,需要在容器启动的时候执行一些内容。比如读取配置文件,数据库连接之类的。SpringBoot给我们提供了两个接口来帮助我们实现这种需求。两个启动加载接口分别是:CommandLineRunner和ApplicationRunner。
他们的执行时机是容器启动完成的时候。

实现启动加载接口

这两个接口中有一个run方法,我们只需要实现这个方法即可。这个两个接口的不同之处在于:
ApplicationRunner中的run方法的参数为ApplicationArguments,而CommandLineRunner接口中run方法的参数为String数组。

ApplicationRunner接口的示例:

package com.jdddemo.demo.controller;
 
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
 
@Component
@Order(value = 1)
public class JDDRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(args);
        System.out.println("这个是测试ApplicationRunner接口");
    }
}

执行结果如下:
在这里插入图片描述

CommandLineRunner接口示例

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
 
@Component
public class TestCommandLineRunner implements CommandLineRunner {
 
    @Override
    public void run(String... args) throws Exception {
        System.out.println("<这个是测试CommandLineRunn接口");
    }
}

CommandLineRunner和ApplicationRunner的执行顺序

在spring boot程序中,我们可以使用不止一个实现CommandLineRunner和ApplicationRunner的bean。为了有序执行这些bean的run()方法,可以使用@Order注解或Ordered接口。
下面例子中创建了两个实现CommandLineRunner接口bean和两个实现ApplicationRunner接口的bean。我们使用@Order注解按顺序执行这四个bean。
CommandLineRunnerBean1.java

@Component
@Order(1)
public class CommandLineRunnerBean1 implements CommandLineRunner {
    @Override
    public void run(String... args) {
        System.out.println("CommandLineRunnerBean 1");
    }
}

ApplicationRunnerBean1.java

@Component
@Order(2)
public class ApplicationRunnerBean1 implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments arg0) throws Exception {
        System.out.println("ApplicationRunnerBean 1");
    }
}

CommandLineRunnerBean2.java

@Component
@Order(3)
public class CommandLineRunnerBean2 implements CommandLineRunner {
    @Override
    public void run(String... args) {
        System.out.println("CommandLineRunnerBean 2");
    }
}

ApplicationRunnerBean2.java

@Component
@Order(4)
public class ApplicationRunnerBean2 implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments arg0) throws Exception {
        System.out.println("ApplicationRunnerBean 2");
    }
}

输出结果为:

CommandLineRunnerBean 1
ApplicationRunnerBean 1
CommandLineRunnerBean 2
ApplicationRunnerBean 2

参考

SpringBoot的ApplicationRunner
CommandLineRunner和ApplicationRunner

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/100251.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!