不应该在Spring Boot中使用CommandLineRunner

总览

在Spring应用程序启动后编写处理方法时,有两种选择:使用CommandLineRunner或ApplicationRunner。哪个应该使用比较好呢?推荐使用ApplicationRunner。
参考链接1:Spring Boot功能/1.10。使用ApplicationRunner或CommandLineRunner。

为什么使用ApplicationRunner(不应使用CommandLineRunner的原因)

引数的处理方法有所不同。反过来说,如果是不使用参数的应用程序,则无论使用哪个都没有问题。举个例子,假设应用程序的参数设置为”arg1 arg2″,当添加参数”–server.port=8081″以更改Web服务器的端口时,就会出现差异。

实例

以下是一个将参数打印到标准输出的程序。

命令行运行器

package com.example.demo;

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(" - CommandLineRunner - ");
        for(int i=0; i<args.length; i++) {
            System.out.printf("%s:%s\n", i, args[i]);
        }
    }

}

应用运行器

package com.example.demo;

import java.util.List;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class TestApplicationRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(" - ApplicationRunner - ");
        List<String> argsList = args.getNonOptionArgs();
        for(int i=0; i<argsList.size(); i++) {
            System.out.printf("%s:%s\n", i, argsList.get(i));
        }
    }

}

通过args.getNonOptionArgs方法,只获取未以” –“开头的参数。

执行结果

如果使用参数”arg1 arg2″运行上述应用程序,结果如下所示。

 - ApplicationRunner - 
0:arg1
1:arg2
 - CommandLineRunner - 
0:arg1
1:arg2

没什么不同。
yì wǒ

在实例中(添加参数的情况下)

例如,为了更改Web服务器的端口,可以添加一个名为”–server.port=8081″的参数。Spring Boot功能-2.外部化配置(参考链接2)

执行结果

如果使用参数”arg1 arg2 –server.port=8081″运行上述应用程序,结果如下所示。

 - ApplicationRunner - 
0:arg1
1:arg2
 - CommandLineRunner - 
0:arg1
1:arg2
2:--server.port=8081

ApplicationRunner的结果没有改变,但CommandLineRunner可以接受额外添加的参数。作为改变Spring Boot行为的参数,在应用程序中是不必要的,因此我认为不应该接受”–server.port=8081″这个参数。当然,也可以接受这个参数。

System.out.println(args.getOptionValues(“server.port”)) => [8081]
=> System.out.println(args.getOptionValues(“server.port”)) => [8081]

当在STS中执行时,” –spring.output.ansi.enabled=always” 会被传入args[0]。

STS的Run Configuration中有一个名为”ANSI console output”的选项,如果勾选上了,那么–spring.output.ansi.enabled参数会自动配置好。如果你正在使用ApplicationRunner,那么可以正确处理这个参数。

行动环境

OpenJDK11.0.2:开放式JDK 11.0.2
Spring Boot 2.3.2:Spring Boot 2.3.2

请引用以下内容,请提供一种中文的本地化版本:

    1. Spring Boot 特性 / 1.10. 使用 ApplicationRunner 或 CommandLineRunner

 

    1. Spring Boot 特性 – 2. 外部化配置

 

    –spring.output.ansi.enabled 配置在哪里?- Stack Overflow
广告
将在 10 秒后关闭
bannerAds