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)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,860评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,936评论 6 342
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,742评论 18 399
  • 文章作者:Tyan博客:noahsnail.com 3.4 Dependencies A typical ente...
    SnailTyan阅读 4,199评论 2 7
  • 昨晚和表哥一起到外婆家吃饭,老人家几个月未见,一看到我们回来就厨房客厅忙里忙外。我给她买了件羊毛衫,穿着合身,她高...
    卷毛维安阅读 6,862评论 41 252