【问题标题】:Configuring Springboot to work with 2 different databases配置 Springboot 以使用 2 个不同的数据库
【发布时间】:2015-03-22 19:45:45
【问题描述】:

我正在学习如何使用 springboot 作为 java 后端框架,我目前已将 applications.properties 配置为使用 1 个数据库。

我正在考虑添加一个额外的数据库来存储不同的信息,而不是将所有内容都保存在一个数据库中,所以我想知道(如果可能的话)我该怎么做?

我的 application.properties 文件包含如下数据:

spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://database:3306...

有什么想法吗?

【问题讨论】:

  • 只需要两个具有不同 bean 或 JNDI 名称的数据源,每个数据源都有自己的连接 URL、驱动程序和凭据。

标签: java mysql database spring spring-boot


【解决方案1】:

您可以创建两个数据源,其中一个 bean 标记为@Primary

@Bean
@ConfigurationProperties(prefix = "datasource.mysql")
public DataSource mysqlDataSource() {
    return DataSourceBuilder.create().build();
}

@ConfigurationProperties(prefix = "datasource.postgres")
@Bean
@Primary
public DataSource postgresDataSource() {                
    return DataSourceBuilder.create().              
            build();
}

您的 application.properties 应如下所示:

datasource.mysql.url=jdbc:mysql://localhost:3306/mysql_demo
datasource.mysql.username=root
datasource.mysql.password=root
datasource.mysql.driverClassName=com.mysql.jdbc.Driver

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

【讨论】:

  • 一个小改进:使用 MySQL 或 Postgres 时不需要指定驱动类名,因为 Spring Boot 会根据 url 自动计算出来
猜你喜欢
  • 2010-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-06
  • 2018-05-14
  • 2012-07-02
  • 1970-01-01
相关资源
最近更新 更多