java - 基于环境的 Spring 数据源

标签 java database spring spring-boot

我正在尝试将我的 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 中,您可以:

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

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

  3. 使用 Spring 配置文件而不是 application.properties,将您的属性放到 application.yaml 中,您可以使用以下约定为所有环境放置属性:

    spring:
        profiles: development
    server:
        port: 9001
    
    ---
    
    spring:
        profiles: production
    server:
        port: 0
    
  4. 使用环境变量并设置 SPRING_DATASOURCE_URLSPRING_DATASOURCE_USERNAMESPRING_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/

相关文章:

php - PDO bindParam 不工作 "bindParam() on a non-object"

java - 为什么Spring MVC会以404响应并报告“在DispatcherServlet中未找到带有URI […]的HTTP请求的映射”?

java - hibernate 5.2.17 : ORA-01797: this operator must be followed by ANY or ALL

database - 逆向工程普适数据库?

database - 如何将 Drupal 数据迁移到 Django?

java - 使用 hibernate 支持多数据库

java - 将 Lucene CharArraySet 转换为 String Set 的最优雅的方法是什么?

java - 如何在配置单元表中插入和检索十进制值

java - 在服务器启动时在 servlet 中调用 Thread.sleep 时 Tomcat 无法启动

java - 使用java递归搜索目录中的.mkv文件