java - 配置 Springboot 以使用 2 个不同的数据库

标签 java mysql database spring spring-boot

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

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

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

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

有什么想法吗?

最佳答案

您可以创建两个数据源,其中一个标记为@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

关于java - 配置 Springboot 以使用 2 个不同的数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28115517/

相关文章:

java - 我应该创建一个新窗口还是修改旧窗口?

php - CodeIgniter 模型无法返回特定记录

mongodb - 数据库复合索引最佳实践 Mongodb

mysql - 如何从数据库中按升序获取随机商店名称和价格?

java - 写入 NFS 存储的文件有时会损坏

java - JDBC 连接中的 URL 为空

Java 程序仅适用于 Netbeans 中的断点

mysql - 编译 Perl 的 DBD::mysql 时如何修复 "Symbol not found: _is_prefix"?

mysql - 使用连接将带有子查询的 MySQL 查询转换为单个查询

SQL 错误 : ORA-00906: missing left parenthesis 00906. 00000 - "missing left parenthesis"