基于环境的Spring数据源

nma*_*rko 11 java database spring spring-boot

我正在尝试配置我的Spring Boot应用程序,以便在存在某些环境变量时使用特定的数据源.例如,如果MY_PROD_DATASOURCE环境变量存在,我想使用我的生产数据源; 否则,我想使用我的本地数据源(相同类型).

在Spring参考中找到了一些解释如何在我的文件中声明单个数据源的内容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
Run Code Online (Sandbox Code Playgroud)

但是,我没有看到如何在此文件中有条件地更改数据源属性.还有另一种方法吗?

Mac*_*iak 13

在Spring Boot中,您可以:

  1. application.properties通过添加路径作为启动参数,从jar中进行外部化并为每个环境提供文件:

    java -jar your-app.jar --spring.config.location=/path/to/app.properties
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用Spring配置文件.application-${profile}.properties为每个配置文件创建每个不同的数据源属性

  3. 使用Spring配置文件代替application.properties,将属性放在application.yaml可以使用约定为所有环境放置属性的位置,如下所示:

    spring:
        profiles: development
    server:
        port: 9001
    
    ---
    
    spring:
        profiles: production
    server:
        port: 0
    
    Run Code Online (Sandbox Code Playgroud)
  4. 使用环境变量和设置SPRING_DATASOURCE_URL,SPRING_DATASOURCE_USERNAME,SPRING_DATASOURCE_PASSWORD,和(可选)SPRING_DATASOURCE_DRIVER_CLASS_NAME.

有关如何根据环境外部配置更改配置的详细信息,请参阅Spring Boot参考部分.