我正在尝试将我的 Spring Boot 应用程序配置为在存在某些环境变量时使用特定的数据源。例如,如果存在 MY_PROD_DATASOURCE
环境变量,我想使用我的生产数据源;否则,我想使用我的本地数据源(相同类型)。
我找到了something in the Spring reference这解释了如何在我的 application.properties
中声明单个数据源。具体来说,MySQL 数据源可能如下所示:
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driverClassName=com.mysql.jdbc.Driver
但是,我看不到如何在此文件中有条件地更改数据源属性。还有其他方法吗?
最佳答案
在 Spring Boot 中,您可以:
从您的 jar 中外部化
application.properties
并通过添加路径作为启动参数来为每个环境提供文件:java -jar your-app.jar --spring.config.location=/path/to/app.properties
使用 Spring 配置文件。在每个不同的数据源属性中为每个配置文件创建
application-${profile}.properties
使用 Spring 配置文件而不是
application.properties
,将您的属性放到application.yaml
中,您可以使用以下约定为所有环境放置属性:spring: profiles: development server: port: 9001 --- spring: profiles: production server: port: 0
使用环境变量并设置
SPRING_DATASOURCE_URL
、SPRING_DATASOURCE_USERNAME
、SPRING_DATASOURCE_PASSWORD
和(可选)SPRING_DATASOURCE_DRIVER_CLASS_NAME
.
在 How to change configuration depending on the environment 上的 Spring Boot 引用部分了解更多信息和 External Configuration .
关于java - 基于环境的 Spring 数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27233536/