基于环境的弹簧数据源
我想配置我的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
不过,我不明白我怎么可以在这个文件中有条件地更改数据源的属性。还有另一种方法可以做到吗?
在春季启动,您可以:从你的罐子
-
外部化
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
了解更多关于How to change configuration depending on the environment的Spring Boot参考部分。
这看起来像我想要做的!然而,我有一个后续问题:这是否意味着我不能在我的应用程序中使用'@ Configuration'和/或'@ EnableAutoConfiguration'注释? – nmagerko 2014-12-01 20:22:15
你可以,你应该。 – 2014-12-01 20:57:48
您可以使用不同的数据源文件定义多个会话工厂。 http://*.com/questions/20541736/hibernate-configuring-multiple-datasources-and-multiple-session-factories – 2014-12-01 17:12:00
你能扩展一点吗?也许在一个答案? – nmagerko 2014-12-01 17:26:59