Spring Boot JPA 数据库选择

12

我如何启动一个独立的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

提前致谢


选择将如何进行?标准是什么? - geoand
2个回答

4

由于您可能需要配置用户名和密码,因此我建议为每个数据源配置创建单独的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=,对吗? - Eric Francis
1
@EricFrancis,你对属性文件的名称是正确的。我已经更正了我的答案。但由于我正在通过命令行传递活动配置文件,所以我不必在spring.profiles.active中指定活动配置文件。 - gyoder
一个 YAML 文件实际上是由 --- 行分隔的一系列文档,每个文档都被单独解析为一个扁平化的映射。如果一个 YAML 文档包含一个 spring.profiles 键,则将配置文件值(逗号分隔的配置文件列表)输入到 Spring Environment.acceptsProfiles() 中,如果其中任何一个配置文件处于活动状态,则该文档将包含在最终合并中(否则不包含)。spring.profiles 属性仅在 YAML 文件中有效。 - hellectronic
请参考文档 https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-change-configuration-depending-on-the-environment。 - hellectronic

0
除了@Profile标签之外,您还可以在Spring Boot中使用标签:@ConditionalOnProperty(name =“propertyName”,havingValue =“propertyValue”),并在每个部署应用程序的环境中声明一个属性来决定要加载哪个数据库!希望能有所帮助!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接