Spring Boot(09)多数据源

tech2024-05-26  76

第09篇:多数据源

流程

配置数据源配置

1. 配置数据源

spring.datasource.test1.jdbc-url=jdbc:mysql://localhost:3306/test1?serverTimezone=Asia/Shanghai spring.datasource.test1.username=root spring.datasource.test1.password=961225 spring.datasource.test1.driver-class-name=com.mysql.jdbc.Driver spring.datasource.test2.jdbc-url=jdbc:mysql://localhost:3306/test2?serverTimezone=Asia/Shanghai spring.datasource.test2.username=root spring.datasource.test2.password=961225 spring.datasource.test2.driver-class-name=com.mysql.jdbc.Driver

2. 配置:数据源、session factory、事务管理器、session template

一共两个数据源,需要实现两个配置类,另一个去除@Primary即可。

@Configuration @MapperScan(basePackages = {"com.example.demo.mapper.test1"}, sqlSessionTemplateRef = "test1SqlSessionTemplate") public class DataSource1Config { @Bean("test1DataSource") @ConfigurationProperties(prefix = "spring.datasource.test1") public DataSource test1DataSource() { return DataSourceBuilder.create().build(); } @Bean("test1SqlSessionFactory") @Primary public SqlSessionFactory test1SqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/test1/*.xml")); return factoryBean.getObject(); } @Bean("test1TransactionManager") @Primary public DataSourceTransactionManager test1TM(@Qualifier("test1DataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean("test1SqlSessionTemplate") @Primary public SqlSessionTemplate test1SqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory factory) { return new SqlSessionTemplate(factory); } }
最新回复(0)