转载至:https://blog.csdn.net/xiaosheng_papa/article/details/80218006
亲测有效。
注:有些系统中已经配置了单数据源,现在要转成多数据源,可能需要额外的配置。拿我自己当前项目来说:
项目在启动类中配置了单数据源:
@Bean(name = "DataSource")//数据源配置
@ConfigurationProperties(prefix = "spring.datasource.db1")//xxx要和server.context-path配置的名称一样
@Primary
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "sqlSessionFactory")//SqlSessionFactory配置
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier("DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:transconf/sql-map-config.xml"));//po对象别名的xml文件
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/**/*.xml"));//mapper的xml文件
return bean.getObject();
}
public SqlSessionFactory sqlSessionFactory(@Qualifier("DataSource") DataSource dataSource) throws Exception {
需要改写成
public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dataSource) throws Exception {