如何在Spring-Boot生产期间覆盖application.properties?

我正在使用spring boot和application.properties在开发期间通过@Configuration @Profile("dev")选择数据库。

 spring.profiles.active=dev spring.config.location=file:d:/application.properties 

在生产过程中,我想创建一个应该加载的应用程序上下文之外的文件,然后使用d:/application.properties激活不同的配置文件:

 spring.profiles.active=production 

结果:当我启动应用程序时,配置仍然是dev ,因此不会考虑生产属性文件的其他位置。 我错过了什么吗?

弹簧靴1.1.0.BUILD-SNAPSHOT

注意:这个问题不是关于tomcat的

我知道你问过怎么做。

但答案是,你不应该这样做。

您可以拥有application.properties application-default.properties application-dev.properties等

您可以通过命令行参数将配置文件切换到jvm

你可以使用@TestPropertySource在测试时覆盖一些东西

理想情况下,所有内容都应该在源代码管理中,这样就不会有任何意外 – 您如何知道服务器位置中存在哪些属性,以及缺少哪些属性。 如果开发人员介绍新事物会发生什么

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

Spring boot已经为你提供了足够的方法来做到这一点。

您也可以使用@PropertySources

 @PropertySources({ @PropertySource(value = "classpath:application.properties"), @PropertySource(value = "file:/user/home/external.properties", ignoreResourceNotFound = true) }) public class Application { public static void main(String[] args) throws Exception { ConfigurableApplicationContext context = SpringApplication.run(Application.class, args); } } 

我不确定您是否可以动态更改配置文件。

为什么不将spring.config.location属性设置为所需的外部位置的内部属性文件,并且该位置(jar外部)的属性文件是否设置了spring.profiles.active属性?

更好的是,有一个特定于dev配置文件的内部属性文件(具有spring.profiles.active = dev)并保持原样,当你想在生产中部署时,为你的属性文件指定一个新的位置,它有spring .profiles.active = PROD:

 java -jar myjar.jar --spring.config.location=D:\wherever\application.properties 

更新:这是spring的一个错误,请看这里

你的jar外面的应用程序属性必须在以下某个位置,然后一切都应该工作。

 21.2 Application property files SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment: A /config subdir of the current directory. The current directory A classpath /config package The classpath root 

所以,例如,当你不想指定cmd line args并且你不在你的基础app.props中使用spring.config.location时,这应该可以工作:

 d:\yourExecutable.jar d:\application.properties or d:\yourExecutable.jar d:\config\application.properties 

请参阅spring external config doc

更新:您可以将\ @Configuration与\ @PropertySource一起使用。 根据这里的文档,您可以在任何地方指定资源。 你应该小心,加载哪个配置以确保你的生产获胜。

我发现以下内容对我有用:

 java -jar my-awesome-java-prog.jar --spring.config.location=file:/path-to-config-dir/ 

file:添加。