如何使用Spring Boot提供不同的数据库配置? [英] How can I provide different database configurations with Spring Boot?

查看:291
本文介绍了如何使用Spring Boot提供不同的数据库配置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前看到它有5个可能的数据库配置文件

As I currently see it I have 5 possible database profiles


  • CI测试 - > h2 mem

  • 开发人员环境(可能是测试或应用程序运行) - > h2 mem,或h2文件,或postgres

  • 生产 - > postgres(理想情况下凭据未存储在git / war中)

目前我已经为运行应用程序配置了postgres,而h2配置为通过具有不同的应用程序进行测试。属性 in java / resource s vs test / resources

currently I have postgres configured for running the application, and h2 configured for testing via having a different application.properties in java/resources vs test/resources

在这些情况下更改数据库连接信息的最简单方法是什么?

what's the simplest way to have the database connection information change for these scenarios?

推荐答案

作为M Deinum在他的评论中提到,最简单的方法是使用配置文件特定配置

As M. Deinum mentions in his comment, the simplest way to do this is to use profile specific configuration.

Spring Boot允许你o有一个通用配置文件( application.properties ),然后有多个其他文件,每个文件都特定于一个配置文件( application - $ {profile} .properties )。

Spring Boot allows you to have one common configuration file (application.properties) and then multiple other files, each specific to a profile (application-${profile}.properties).

例如:


  • application.properties - 常用配置

  • application-dev.properties - 配置dev profile

  • application-ci.properties - ci配置文件的配置

  • application.properties - Common configuration
  • application-dev.properties - Configuration for dev profile
  • application-ci.properties - Configuration for ci profiles

例如,如果您的应用程序以ci配置文件运行,则将加载默认配置文件以及ci配置文件(包含ci配置文件的数据源配置属性)。

If your application runs with "ci" profile for instance, the default configuration file as well as the ci configuration file (which would contain the datasource configuration properties for ci profile) will be loaded.

要切换配置文件,您可以使用以下选项之一:

To switch profiles you can use one of the following options:


  • JVM属性: -Dspring.profiles.active = ci

  • 命令行开关: - spring.profiles.active = dev

  • JVM property: -Dspring.profiles.active=ci
  • Command line switch: --spring.profiles.active=dev

单位测试可以在测试类上使用 @ActiveProfiles(test)注释告诉Spring应该使用测试配置文件运行单元测试。

For unit tests you can use @ActiveProfiles("test") annotation on your test classes to tell Spring that unit tests should be run with test profile.

此外,如果您不想将生产数据库凭据与源代码一起存储,则可以在生产中部署应用程序时指定外部配置文件:

Also if you don't want to store production database credentials along with your source code, you can specify external configuration file when you deploy your app in production:


  • 使用命令行开关: - spring.config.location = / srv / myapp / config.properties

  • 使用JVM属性: -Dspring.config.location = / srv / myapp / config.properties

  • Using command line switch: --spring.config.location=/srv/myapp/config.properties
  • Using a JVM property: -Dspring.config.location=/srv/myapp/config.properties

这篇关于如何使用Spring Boot提供不同的数据库配置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆