问题
I have a spring-boot application. I want to override some properties which was configuration in application.yml when executing the jar.
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
@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
name: nameInApplication
when I excute the command like that:
java -jar app.jar --name=nameInCommand
It's not work
The Second command also not work:
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.
回答1:
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);
}
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. 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(...)?
来源:https://stackoverflow.com/questions/42244380/override-yml-configuration-in-spring-boot-with-command-line-arguments-not-work