【问题标题】:Spring Boot JPA Database ChoiceSpring Boot JPA 数据库选择
【发布时间】:2014-10-21 06:14:45
【问题描述】:

如何启动一个独立的 Spring Boot JPA 应用程序——而不是通过 cli——选择数据库来获取数据,例如 localhost:5432/my_db;或 192.168.1.100:5432/our_db,还是 example.com:5432/their_db?

我的当前使用的是 application.properties 文件中包含的一个:

spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/my_db
spring.datasource.username=postgres
spring.datasource.password=postgres

spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create

提前致谢

【问题讨论】:

  • 将如何选择?标准是什么?

标签: postgresql jpa spring-boot


【解决方案1】:

由于您可能还需要配置用户名和密码,我建议为每个数据源配置创建单独的application-mydatasource.properties 文件。然后,您将根据设置活动配置文件激活要使用的数据源。您可以在 application.properties (spring.profiles.active) 或通过命令行参数设置活动配置文件:

$ java -jar -Dspring.profiles.active=mydatasource demo-0.0.1-SNAPSHOT.jar

application-mydatasource.properties 将覆盖 application.properties 中的所有属性。我相信您还需要将spring.profiles= 设置为可用配置文件列表。

Profile specific properties

【讨论】:

  • 我认为属性文件必须采用这种格式:application-{profile}.properties。另外,spring.profiles= 应该是 spring.profiles.active=,对吗?
  • @EricFrancis,您对属性文件的名称是正确的。我更正了我的答案。但由于我将活动配置文件作为命令行传递,我不必在 spring.profiles.active 中指定活动配置文件。
  • "一个YAML文件实际上是一个由---行分隔的文档序列,每个文档单独解析成一个扁平化的map。如果一个YAML文档包含spring.profiles键,那么profiles值(以逗号分隔的配置文件列表)被馈送到 Spring Environment.acceptsProfiles() 中,如果这些配置文件中的任何一个处于活动状态,则该文档将包含在最终合并中(否则不包含)。 spring.profiles 属性仅在 YAML 文件中有效。
【解决方案2】:

除了@Profile 标签之外的另一个选项,您必须在每个环境中声明您将部署应用程序,您可以在 Spring Boot 中使用该标签:

@ConditionalOnProperty(name="propertyName", havingValue="propertyValue")

并声明一个属性来决定每种情况下要加载的数据库!

希望有所帮助!

【讨论】:

    猜你喜欢
    • 2017-08-22
    • 2021-05-04
    • 2019-11-10
    • 2022-01-11
    • 2017-02-20
    • 2020-02-08
    • 2021-08-17
    • 2017-11-06
    • 1970-01-01
    相关资源
    最近更新 更多