Override yml configuration in spring-boot with command line arguments not working

I have a spring-boot application. I want to override some properties that were settings in application.yml when executing a jar.

My code is:

@Service public class CommandService { @Value("${name:defaultName}") private String name; public void print() { System.out.println(name); } } 

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

.Yml application

name: nameInApplication

when I clean the command as follows:

java -jar app.jar --name = nameInCommand

Does not work

The second command also does not work:

java -Dname = nameInCommand2 -jar app.jar

But if application.yml does not have a configuration name, the second command will work well, and the first command will not work either.

+3
source share
1 answer

This is a few months ago, but I'm going to answer it, because I just ran into this problem and found your question through Google, and Ivan commented on the run in my memory. Since he didn’t specify, and I’m not sure if you solved your problem (probably you are already), you will 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); } 

It's simple. Arguments before this never went anywhere when they passed, thus not overriding the application.yml property. So just in case, if you did not understand this or someone stumbled upon this question, like me, this is what Ivan had in mind

Do you pass command line arguments when running SpringApplication.run(...) ?

+3
source

Source: https://habr.com/ru/post/985531/


All Articles