spring boot druid mybatis多数据源
一、关闭数据源自动配置(很关键)
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
如果不关闭会报异常:org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'dataSource': Requested bean is currently in creation: Is there an unresolvable circular reference?
ps:之前一直没折腾成功,竟然就是少了这一个配置,泪奔
二、配置文件
spring.datasource.druid.one.driver-class-name=com.mysql.jdbc.Driver spring.datasource.druid.one.url= spring.datasource.druid.one.username= spring.datasource.druid.one.password= spring.datasource.druid.two.driver-class-name=com.mysql.jdbc.Driver spring.datasource.druid.two.url= spring.datasource.druid.two.username= spring.datasource.druid.two.password=
三、数据源定义
@Bean @ConfigurationProperties("spring.datasource.druid.one") public DataSource dataSource1() throws Exception { return DruidDataSourceBuilder.create().build(); } @Bean @ConfigurationProperties("spring.datasource.druid.two") public DataSource dataSource2() throws Exception { return DruidDataSourceBuilder.create().build(); }
四、多数据类定义
package com.qmtt.config; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DynamicDataSourceHolder.getDataSourceKey(); } }
五、ThreadLocal定义
package com.qmtt.config; import java.util.HashSet; import java.util.Set; public class DynamicDataSourceHolder { private static final ThreadLocal<String> dataSourceThreadLocal = new ThreadLocal<String>(); private static Set<String> dataSourceKeys = new HashSet<String>(); static { dataSourceKeys.add("master"); dataSourceKeys.add("slave"); } public static void setDataSourceKey(String dataSourceKey) { dataSourceThreadLocal.set(dataSourceKey); } public static String getDataSourceKey() { return dataSourceThreadLocal.get(); } public static void clearDataSourceKey() { dataSourceThreadLocal.remove(); } public static boolean containsDataSourceKey(String dataSourceKey) { return dataSourceKeys.contains(dataSourceKey); } }
六、数据源定义
@Bean public DataSource dataSource(@Qualifier("dataSource1") DataSource dataSource1, @Qualifier("dataSource2") DataSource dataSource2) throws Exception { DynamicDataSource dynamicDataSource = new DynamicDataSource(); // 创建默认数据源 dynamicDataSource.setDefaultTargetDataSource(dataSource1()); // 配置多数据源 Map<Object, Object> dataSourceMap = new HashMap<>(4); dataSourceMap.put("master", dataSource1); dataSourceMap.put("slave", dataSource2); dynamicDataSource.setTargetDataSources(dataSourceMap); return dynamicDataSource; }
七、SqlSessionFactory定义
常规写法
八、AOP切换
Aspect拦截dao就行
第一步很关键