我使用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
,所以不知何故,没有考虑到生产属性文件的额外位置。我错过什么了吗?
spring boot 1.1.0.BUILD-SNAPSHOT
注意:这个问题是不是对 tomcat 。
我知道你问怎么做,但答案是你不应该这样做。
应该使用application.properties
、application-default.properties
、application-dev.properties
等,并通过参数将配置文件切换到JVM:例如-Dspring.profiles.active=dev
您也可以在测试时使用@TestPropertySource
理想情况下,所有的东西都应该在源代码控制中,这样就不会有意外,例如,你怎么知道服务器位置上有哪些属性,哪些属性丢失了?如果开发者引入新内容会发生什么?
Spring Boot已经为您提供了足够的方法来正确执行此操作。
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html您也可以使用@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。激活属性设置?
更好的是,有一个内部属性文件,特定于开发配置文件(有spring.profiles.active=dev),并保持不变,当您想要在生产中部署时,为您的属性文件指定一个新位置,它有spring.profiles.active=prod:
java -jar myjar.jar --spring.config.location=D:whereverapplication.properties
从Spring Boot 2开始,您必须使用
--spring.config.additional-location=production.properties
Update with Spring Boot 2.2.2.Release.
完整的例子在这里,https://www.surasint.com/spring-boot-override-property-example/
假设在您的jar文件中有应用程序。属性包含以下两行:
server.servlet.context-path=/test
server.port=8081
然后,在生产环境中,您希望重写服务器。Port =8888,但您不想覆盖其他属性。
首先创建另一个文件,例如override。属性并联机这一行:
server.port=8888
然后你可以像这样启动jar
java -jar spring-boot-1.0-SNAPSHOT.jar --spring.config.location=classpath:application.properties,/opt/somewhere/override.properties
更新:这是春天的一个bug,看这里
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行参数,并且你不使用spring.config.location在你的base app.props:
d:yourExecutable.jar
d:application.properties
or
d:yourExecutable.jar
d:configapplication.properties
参见spring external config doc
更新:您可以将@Configuration与@PropertySource一起使用。根据这里的文档,你可以在任何地方指定资源。当加载哪个配置时,您应该小心,以确保您的生产配置获胜。
我发现以下方法对我有效:
java -jar my-awesome-java-prog.jar --spring.config.location=file:/path-to-config-dir/
添加 file:
。
当然,这个命令行是,永远不会像在生产环境中那样运行。
而不是
- [可能是几层]
shell
脚本在源代码控制与占位符的所有部分的命令,可以改变(jar的名称,路径配置…) -
ansible
部署脚本,将部署shell
脚本并用实际值替换占位符。
spring配置优先级如下:
- ServletConfig init Parameter
- ServletContext初始化参数 JNDI属性
- System.getProperties ()
因此,如果您希望这样做,您的配置将在命令行中被覆盖。尽管您可以使用多个配置文件,但建议避免重写。