我们何时以及为什么需要 ApplicationRunner 和 Runner 接口?

2022-09-01 15:48:25

我正在学习弹簧靴。ApplicationRunner 或任何运行器接口有哪些典型用例?

import org.junit.jupiter.api.Test;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class PersistencedemoApplicationTests implements ApplicationRunner {

    @Test
    void contextLoads() {
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
       // load initial data in test DB
    }
}

这是我所知道的一个案例。别的东西?


答案 1

这些运行器用于在应用程序启动时运行逻辑,例如spring boot具有AppplicationRunner(功能接口)与方法run

ApplicationRunner run() 将在应用程序上下文创建之后和 Spring Boot 应用程序启动之前执行。

ApplicationRunner采用AppuseArgument,它具有方便的方法,如getOptionNames(),getOptionValues()和getSourceArgs()。

而CommandLineRunner也是一个带有方法的功能接口run

CommandLineRunner run() 将在应用程序上下文创建之后和 Spring Boot 应用程序启动之前执行。

它接受在服务器启动时传递的参数。

它们都提供相同的功能,并且 和 之间的唯一区别是接受,而接受为参数。您可以在此处找到有关示例的更多信息CommandLineRunnerApplicationRunnerCommandLineRunner.run()String array[]ApplicationRunner.run()ApplicationArguments


答案 2

为了使用 ApplicationRunnerCommandLineRunner 接口,需要创建一个 Spring Bean 并实现 ApplicationRunnerCommandLineRunner 接口,两者的性能相似。完成后,您的Spring应用程序将检测您的Bean。

此外,您可以创建多个 ApplicationRunnerCommandLineRunner Bean,并通过实现

  • org.springframework.core.Ordered interface

  • org.springframework.core.annotation.Order annotation.

用例:

  1. 人们可能希望记录一些命令行参数。

  2. 您可以在终止此应用程序时向用户提供一些说明。

考虑:

@Component
public class MyBean implements CommandLineRunner {

    @Override
    public void run(String...args) throws Exception {
        logger.info("App started with arguments: " + Arrays.toString(args));
    }
}

有关应用程序运行程序的详细信息


推荐