SpringBoot 配置多数据源

1. 配置多数据源DataSource

## 配置datasource
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.klin")
    @Primary // 标识当前为默认数据源
    DataSource klin(){
        return DataSourceBuilder.create().build();
    }
## 配置sqlSessionFactory
    @Bean("klinSqlSessionFactory")
    @Primary
    SqlSessionFactory klinSqlSessionFactory(@Qualifier("klin") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        // setMapperLocations 设置mapper配置地址
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResource("classpath:mapping/klin/DictMapper.xml"));
        return sqlSessionFactoryBean.getObject();
    }
## 配置SqlSessionTemplate
    @Bean("klinSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate klinSqlSessionTemplate(@Qualifier("klinSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
## 使用mapperScan指定数据源地址
@MapperScan(basePackages = "com/bu/firstdoc/klin/mapper/",sqlSessionFactoryRef = "klinSqlSessionFactory")



你可能感兴趣的:(SpringBoot 配置多数据源)