SpringBoot整合多数据源xml方式

项目中遇到需要连接多个数据库,本来使用SpringBoot默认配置连接是非常简单的,但是由于涉及多个数据库,不得不再自定义配置了,一次性整明白,下次就之间copy使用。

  • 1.首先学习一个注解@ConfigurationProperties(prefix = "druid")

默认注入,配置文件中druid开头的属性。eg:

druid.url=jdbc:postgresql://139.198.x.x:1x020/account
druid.url2=jdbc:postgresql://139.198.x.x:1x020/oto_saas
druid.driver-class=org.postgresql.Driver
druid.username=root
druid.password=XXX123
druid.initial-size=1
druid.min-idle=1
druid.max-active=20
druid.test-on-borrow=true
druid.timeBetweenEvictionRunsMillis=9000




/**
 *
 * @author liuxin
 * @since 2017/4/19
 */
@ConfigurationProperties(prefix = "druid")
public class DruidProperties {
    private String url;
    private String url2;
    private String username;
    private String password;
    private String driverClass;
    private int maxActive;//最大连接数
    private int minIdle;//最小连接数
    private int initialSize;//初始化数量和
    private boolean testOnBorrow;
    private Long timeBetweenEvictionRunsMillis;//心跳
  • 2.添加数据源配置A
    /**
     * @Package: pterosaur.account.config.druid
     * @Description: account 数据源1
     * @author: liuxin
     * @date: 17/4/21 下午7:11
     */
    @Configuration
    @EnableConfigurationProperties(DruidProperties.class) //开启属性注入,通过@autowired注入 //注入DruidProerties,就是根据第一个注解,创建的配置类
    @ConditionalOnClass(DruidDataSource.class)//判断这个类是否在classpath中存在
    @ConditionalOnProperty(prefix = "druid", name = "url")
    @MapperScan(basePackages = "pterosaur.account.mapper.account", sqlSessionTemplateRef  = "accountSqlSessionTemplate")//配置实体类包
    public class DruidAutoConfiguration1 {
        @Autowired
        private DruidProperties properties;

        @Bean(name = "accountDataSource") 
        @Primary  //DataSource 是一个接口,因为是两个数据源,所以用Primary标记其中一个,防止报错
        public DataSource dataSource() {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(properties.getUrl());
            dataSource.setUsername(properties.getUsername());
            dataSource.setPassword(properties.getPassword());
            dataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
            if (properties.getInitialSize() > 0) {
                dataSource.setInitialSize(properties.getInitialSize());
            }
            if (properties.getMinIdle() > 0) {
                dataSource.setMinIdle(properties.getMinIdle());
            }
            if (properties.getMaxActive() > 0) {
                dataSource.setMaxActive(properties.getMaxActive());
            }
            dataSource.setTestOnBorrow(properties.isTestOnBorrow());
            try {
                dataSource.init();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            return dataSource;
        }


        @Bean(name = "accountSqlSessionFactory")
        @Primary //同上
        public SqlSessionFactory testSqlSessionFactory(@Qualifier("accountDataSource") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/account/*.xml"));
            return bean.getObject(); //配置映射文件地址
        }

        @Bean(name = "accountTransactionManager")
        @Primary
        public DataSourceTransactionManager testTransactionManager(@Qualifier("accountDataSource") DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean(name = "accountSqlSessionTemplate")
        @Primary
        public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("accountSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    }
  • 3.添加数据源配置B
    package pterosaur.account.config.druid;

    import com.alibaba.druid.pool.DruidDataSource;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.mybatis.spring.SqlSessionTemplate;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.boot.autoconfigure.AutoConfigureBefore;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
    import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
    import org.springframework.jdbc.datasource.DataSourceTransactionManager;

    import javax.sql.DataSource;
    import java.sql.SQLException;

    /**
     * @Package: pterosaur.account.config.druid
     * @Description: otosaas 数据源2
     * @author: liuxin
     * @date: 17/4/21 下午7:11
     */
    @Configuration
    @EnableConfigurationProperties(DruidProperties.class)
    @ConditionalOnClass(DruidDataSource.class)
    @ConditionalOnProperty(prefix = "druid", name = "url")
    @MapperScan(basePackages = "pterosaur.account.mapper.otosaas", sqlSessionTemplateRef  = "otoSaaSSqlSessionTemplate")
    public class DruidAutoConfiguration2 {
        @Autowired
        private DruidProperties properties;

        @Bean(name = "otoSaaSDataSource")
        public DataSource dataSource() {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(properties.getUrl2());
            dataSource.setUsername(properties.getUsername());
            dataSource.setPassword(properties.getPassword());
            dataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
            if (properties.getInitialSize() > 0) {
                dataSource.setInitialSize(properties.getInitialSize());
            }
            if (properties.getMinIdle() > 0) {
                dataSource.setMinIdle(properties.getMinIdle());
            }
            if (properties.getMaxActive() > 0) {
                dataSource.setMaxActive(properties.getMaxActive());
            }
            dataSource.setTestOnBorrow(properties.isTestOnBorrow());
            try {
                dataSource.init();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            return dataSource;
        }


        @Bean(name = "otoSaaSSqlSessionFactory")
        public SqlSessionFactory testSqlSessionFactory(@Qualifier("otoSaaSDataSource") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/otosaas/*.xml"));
            return bean.getObject();
        }

        @Bean(name = "accountTransactionManager")
        public DataSourceTransactionManager testTransactionManager(@Qualifier("otoSaaSDataSource") DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean(name = "otoSaaSSqlSessionTemplate")
        public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("otoSaaSSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    }

参考地址
代码地址

@ConditionalOnBean(仅仅在当前上下文中存在某个对象时,才会实例化一个Bean)
@ConditionalOnClass(某个class位于类路径上,才会实例化一个Bean)
@ConditionalOnExpression(当表达式为true的时候,才会实例化一个Bean)
@ConditionalOnMissingBean(仅仅在当前上下文中不存在某个对象时,才会实例化一个Bean)
@ConditionalOnMissingClass(某个class类路径上不存在的时候,才会实例化一个Bean)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

西魏陶渊明

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值