在Spring Boot项目中配置多数据源的步骤如下:
- 在
application.properties
或application.yml
中配置不同数据源的连接信息。
application.properties
配置示例:
# 数据源1配置
spring.datasource.primary.jdbc-url=jdbc:postgresql://localhost:5432/db_primary
spring.datasource.primary.username=user_primary
spring.datasource.primary.password=pass_primary
# 数据源2配置
spring.datasource.secondary.jdbc-url=jdbc:postgresql://localhost:5432/db_secondary
spring.datasource.secondary.username=user_secondary
spring.datasource.secondary.password=pass_secondary
- 创建数据源配置类,使用
@Configuration
和@Bean
注解来定义数据源。
DataSourceConfig.java
配置示例:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
@Configuration
public class DataSourceConfig {
@Primary
@Bean(name = "primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
}
- 配置JPA或JDBC模板,为每个数据源指定对应的数据源。
PrimaryJpaConfig.java
配置示例:
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(