简体   繁体   English

使用命令行参数覆盖spring-boot中的yml配置不起作用

[英]Override yml configuration in spring-boot with command line arguments not work

I have a spring-boot application. 我有一个spring-boot应用程序。 I want to override some properties which was configuration in application.yml when executing the jar. 我想在执行jar时覆盖application.yml中配置的一些属性。

My code like this: 我的代码是这样的:

@Service
public class CommandService {

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

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

And the Application.java is 而Application.java是

@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();
    }
}

The application.yml application.yml

name: nameInApplication name:nameInApplication

when I excute the command like that: 当我执行这样的命令时:

java -jar app.jar --name=nameInCommand java -jar app.jar --name = nameInCommand

It's not work 这不行

The Second command also not work: 第二个命令也不起作用:

java -Dname=nameInCommand2 -jar app.jar java -Dname = nameInCommand2 -jar app.jar

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. 但是如果application.yml没有配置名称,第二个命令将运行良好,第一个命令也无法正常工作。

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. 这已经有几个月了,但是我要回答它,因为我刚遇到这个问题并通过谷歌和Ivan的评论发现了你的问题。 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);
}

to

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

That simple. 那么简单。 The arguments before were never going anywhere when they got passed in thus not overriding your application.yml property. 传递之前的参数永远不会去任何地方,因此不会覆盖你的application.yml属性。 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 所以,如果你没有弄清楚,或者有人像我一样偶然发现了这个问题,那就是伊万的意思

do you pass command line arguments when starting SpringApplication.run(...) ? 在启动SpringApplication.run(...)时是否传递命令行参数?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM