请提供springboot连接双数据源的方法以及使用例子
时间: 2023-02-23 15:27:40 浏览: 83
Spring Boot 支持连接多个数据源。在使用多个数据源时,您可以使用 @Primary 注解来指定默认数据源。
下面是一个使用 Spring Boot 连接双数据源的简单示例:
1. 在 application.properties 文件中配置两个数据源的连接信息:
```
# DataSource 1
spring.datasource.first.jdbc-url=jdbc:mysql://localhost:3306/db1
spring.datasource.first.username=root
spring.datasource.first.password=password
# DataSource 2
spring.datasource.second.jdbc-url=jdbc:mysql://localhost:3306/db2
spring.datasource.second.username=root
spring.datasource.second.password=password
```
2. 创建两个数据源配置类,分别定义两个数据源的连接:
```
@Configuration
public class FirstDataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.first")
public DataSource firstDataSource() {
return DataSourceBuilder.create().build();
}
}
@Configuration
public class SecondDataSourceConfig {
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.second")
public DataSource secondDataSource() {
return DataSourceBuilder.create().build();
}
}
```
3. 在实体类中指定使用哪个数据源:
```
@Entity
@Table(name = "table_name")
@org.springframework.data.jpa.repository.config.EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactoryFirst",
basePackages = {"com.example.first.repository"}
)
public class Entity {
// ...
}
@Entity
@Table(name = "table_name")
@org.springframework.data.jpa.repository.config.EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactorySecond",
basePackages = {"com.example.second.repository"}
)
public class Entity {
// ...
}
```
4. 在仓库接口中指定使用哪个数据源:
```
@Repository
public interface FirstRepository extends J
阅读全文
相关推荐


















