使用命令行参数覆盖spring-boot中的yml配置不起作用 [英] Override yml configuration in spring-boot with command line arguments not work

查看:153
本文介绍了使用命令行参数覆盖spring-boot中的yml配置不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个spring-boot应用程序.我想在执行jar时覆盖在application.yml中配置的某些属性.

I have a spring-boot application. I want to override some properties which was configuration in application.yml when executing the jar.

我的代码如下:

@Service
public class CommandService {

    @Value("${name:defaultName}")
    private String name;

    public void print() {
        System.out.println(name);
    }
}

Application.java是

And the Application.java is

@SpringBootApplication
public class Application implements CommandLineRunner {

    @Autowired
    private CommandService commandService;

    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }

    @Override
    public void run(String... args) throws Exception {
        commandService.print();
    }
}

application.yml

The application.yml

名称:nameInApplication

name: nameInApplication

当我执行这样的命令时:

when I excute the command like that:

java -jar app.jar --name = nameInCommand

java -jar app.jar --name=nameInCommand

这是行不通的

第二个命令也不起作用:

The Second command also not work:

java -Dname = nameInCommand2 -jar app.jar

java -Dname=nameInCommand2 -jar app.jar

但是,如果application.yml没有配置名称,则第二个命令将正常运行,而第一个命令也将无法正常工作.

But if the application.yml not have config the name, the second command will work well and the first command also not work any way.

推荐答案

这已经几个月了,但是我要回答这个问题,因为我刚遇到这个问题,并通过google找到了您的问题,而Ivan的评论则使我感到困惑记忆.由于他没有详细说明,而且我不确定您是否已解决问题(现在可能已经解决了),因此您将需要更改:

This is a few months old, but I'm going to answer it because I just ran into this issue and found your question via google and Ivan's comment jogged my memory. Since he did not elaborate and I'm not sure if you solved your issue (you probably have by now), you are going to want to change:

public static void main(String[] args) {
    SpringApplication.run(Application.class);
}

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

那很简单.之前的参数传入时永远不会流到任何地方,因此不会覆盖您的application.yml属性.因此,以防万一您还没有弄清楚它,或者如果有人像我一样偶然发现了这个问题,这就是Ivan所指的

That simple. The arguments before were never going anywhere when they got passed in thus not overriding your application.yml property. So just in case you haven't figured it out or if someone stumbled upon this question like I did, that is what Ivan meant by

启动时是否传递命令行参数 SpringApplication.run(...)?

do you pass command line arguments when starting SpringApplication.run(...)?

这篇关于使用命令行参数覆盖spring-boot中的yml配置不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆