springboot集成多个数据源

@Configuration
@MapperScan(
basePackages="com.*****.dal.casmapper",
sqlSessionFactoryRef="sqlSessionFactory1",
sqlSessionTemplateRef = "sqlSessionTemplate1")
public class CasDataSourceConfig {

    @Bean("dataSource1")
    public DataSource dataSource1()throws Exception{

        Map properties = new HashMap<>();
        properties.put("driverClassName","com.mysql.jdbc.Driver");
        properties.put("url","jdbc:mysql://********:3306/cas");
        properties.put("username","****");
        properties.put("password","*****");
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        return dataSource;

    }

    @Bean("sqlSessionFactory1")
    public SqlSessionFactory sqlSessionFactory1()throws Exception{
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource1());
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:casmapper/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean("sqlSessionTemplate1")
    public SqlSessionTemplate sqlSessionTemplate1()throws Exception{
        SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory1());
        return sqlSessionTemplate;
    }
}

注意:
根据@MapperScan中的basePackages配置mapper接口位置,根据sqlSessionFactoryRef 配置此数据源的sqlSessionFactory,根据sqlSessionTemplateRef 配置此数据源的sqlSessionTemplate,亲测可用

你可能感兴趣的:(springboot集成多个数据源)