简体   繁体   English

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

[英]Configuring Springboot to work with 2 different databases

I am just learning how to use springboot as a java backend framework and I currently have applications.properties configured to use 1 database. 我只是在学习如何将springboot用作Java后端框架,并且我目前已将applications.properties配置为使用1个数据库。

I am thinking of adding an additional database to store different information instead of saving everything on a single database so I was wondering how (if possible) can i do that? 我正在考虑添加一个额外的数据库来存储不同的信息,而不是将所有内容保存在一个数据库中,所以我想知道如何(如果可能)做到这一点?

My application.properties file contains data like this: 我的application.properties文件包含如下数据:

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

Any ideas? 有任何想法吗?

You can create two datasources, one bean of them mark as @Primary 您可以创建两个数据源,其中一个标记为@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();
}

Your application.properties should looks like this: 您的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM