我们知道,我们可以通过@Value注释来外部化配置,就像在 Spring 引导项目中一样。
@Value("${max.routes}")
private int maxRoutes;
在这种情况下,我们在注释参数本身中给出默认值,如下方式,
@Value("${max.routes:10}")
private int maxRoutes;
我们可以在启动此应用程序时通过传递 VM 参数来覆盖该值吗?
例如,-Dmax.routes=20
. 它会覆盖该值吗?
是的,系统属性和命令行参数将覆盖这些属性值。
如果您像这样运行应用程序...
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
。您可以使用-Dmax.routes=20
甚至应用程序参数--max.routes=20
覆盖您的属性。应用程序参数将具有高优先级。
看看 Spring boot 文档的外部化配置部分:
Spring 引导允许您外部化配置,以便您可以在不同的环境中使用相同的应用程序代码。
它对配置源的优先级有非常严格的规则:
1 . Devtools global settings properties on your home directory (~/.spring-boot-devtools.properties when devtools is active).
2 . @TestPropertySource annotations on your tests.
3 . @SpringBootTest#properties annotation attribute on your tests.
4 . Command line arguments.
5 . Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).
6 . ServletConfig init parameters.
7 . ServletContext init parameters.
8 . JNDI attributes from java:comp/env.
9 . Java System properties (System.getProperties()).
10. OS environment variables.
11. A RandomValuePropertySource that has properties only in random.*.
12. Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants).
13. Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants).
14. Application properties outside of your packaged jar (application.properties and YAML variants).
15. Application properties packaged inside your jar (application.properties and YAML variants).
16. @PropertySource annotations on your @Configuration classes.
17. Default properties (specified by setting SpringApplication.setDefaultProperties).
例如,在application.propertis中定义的属性将被OS env变量覆盖,Java系统属性将被覆盖它们,基本上命令行参数将在您不运行测试时覆盖所有内容。