How to configure multiple data sources in SpringBoot?
To configure multiple data sources in SpringBoot, you can follow these steps:
Configure data source information in the application.properties or application.yml file, for example:
# 第一个数据源
spring.datasource.url=jdbc:mysql://localhost:3306/db1
spring.datasource.username=user1
spring.datasource.password=password1
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 第二个数据源
custom.datasource.url=jdbc:mysql://localhost:3306/db2
custom.datasource.username=user2
custom.datasource.password=password2
custom.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
Create configuration classes for two data sources, configuring them using the @Configuration and @Bean annotations, for example:
@Configuration
public class DataSourceConfig {
@Primary
@Bean(name = "dataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "customDataSource")
@ConfigurationProperties(prefix = "custom.datasource")
public DataSource customDataSource() {
return DataSourceBuilder.create().build();
}
}
3. Use the @Qualifier annotation to specify the name of the data source where it is needed.
@Service
public class UserService {
@Autowired
@Qualifier("dataSource")
private DataSource dataSource;
@Autowired
@Qualifier("customDataSource")
private DataSource customDataSource;
}
You can configure multiple data sources in Spring Boot and specify a specific data source where needed by following the steps above.