我刚刚学习如何使用 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/