繁体   English   中英

根据环境变量设置Spring Boot application.properties

[英]Set Spring Boot application.properties based on Environment Variable

我有一个将在各种环境中运行的Spring Boot应用程序,并且根据它运行的环境,它将连接到不同的数据库。 我有一些application.properties文件,每个环境对应一个文件:

application-local.properties

spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=dbuser
spring.datasource.password=123456789

application-someserver.properties

spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://someserver:5432/myproddb
spring.datasource.username=produser
spring.datasource.password=productionpass

等等

在我的每个环境中,我都有一个名为MYENV的环境变量,它被设置为环境类型,例如localsomeserverapplication-{env}.properties文件的名称与环境名称完全匹配)。

如何让spring boot读取此环境变量并自动选择正确的.properties文件? 我不想做整个-Dspring.profiles.active=someserver因为这个包的部署方式(它不会作为jar运行)。

如何让spring boot读取此环境变量并自动选择正确的.properties文件?

告诉Spring Boot从MYENV属性或环境变量中选择Active Profile 一种方法是将以下内容添加到application.properties

spring.profiles.active=${MYENV}

这样Spring Boot会将spring.profiles.active设置为MYENV环境变量的值。

我不必做整个-Dspring.profiles.active = someserver,因为这个包的部署方式(它不会作为jar运行)

如果您不想通过-D参数传递系统属性,则可以将相应的环境变量用于spring.profiles.active 相应的环境变量是SPRING_PROFILES_ACTIVE 例如,如果将SPRING_PROFILES_ACTIVE设置为local ,则将激活local配置文件。 如果你坚持使用MYENV环境变量,第一个解决方案就是要走的路。

如果要将该应用程序部署到某个容器(tomcat,weblogic,...),则可以指定环境变量。 例如,让我们指定环境变量application1.spring.profiles.active=someserver ,然后在你的application.properties中设置属性spring.profiles.active=${application1.spring.profiles.active}

使用Spring context 5.0我已经通过以下注释成功地基于系统环境加载了正确的属性文件

@PropertySources({
    @PropertySource("classpath:application.properties"),
    @PropertySource("classpath:application-${MYENV:test}.properties")})

这里从系统环境读取MYENV值,如果系统环境不存在,则将加载默认测试环境属性文件,如果我给出错误的MYENV值 - 它将无法启动应用程序。

注意:对于每个配置文件,您希望维护需要创建application- [profile] .property文件,尽管我使用的是Spring上下文5.0 而不是Spring引导 - 我相信这也适用于Spring 4.1

这是我相信我的AWS Lambda的最佳解决方案 - 具有最小的依赖性

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM