springboot配置双数据源
时间: 2023-06-28 20:11:19 浏览: 54
在Spring Boot中配置多个数据源可以通过创建多个DataSource Bean并在每个Bean上使用@Qualifier注释来实现。以下是一个简单的双数据源配置示例:
1. 在application.properties文件中配置两个数据源的连接信息:
```
# Primary datasource
spring.datasource.url=jdbc:mysql://localhost:3306/db1
spring.datasource.username=user1
spring.datasource.password=pass1
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# Secondary datasource
spring.second-datasource.url=jdbc:mysql://localhost:3306/db2
spring.second-datasource.username=user2
spring.second-datasource.password=pass2
spring.second-datasource.driver-class-name=com.mysql.jdbc.Driver
```
2. 创建两个数据源的Bean:
```java
@Configuration
public class DataSourceConfig {
@Bean
@Primary
@ConfigurationProperties(prefix="spring.datasource")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix="spring.second-datasource")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
}
```
在这里,我们使用了@ConfigurationProperties注释来自动装配数据源的属性,因此不必在Java代码中硬编码它们。
3. 创建两个JdbcTemplate Bean,并将它们与对应的数据源Bean关联起来:
```java
@Configuration
public class JdbcTemplateConfig {
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean(name = "secondJdbcTemplate")
public JdbcTemplate secondJdbcTemplate(@Qualifier("secondaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
```
在这里,我们使用了@Qualifier注释来区分两个数据源Bean,并且将其传递给JdbcTemplate Bean。
现在,我们已经成功地配置了两个数据源。要在代码中使用它们,请注入相应的JdbcTemplate Bean,如下所示:
```java
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
@Qualifier("secondJdbcTemplate")
private JdbcTemplate secondJdbcTemplate;
```
您现在可以使用jdbcTemplate和secondJdbcTemplate执行操作,以便在两个不同的数据库中存储和检索数据。