SpringBoot整合多数据源xml方式

举报
西魏陶渊明 发表于 2022/09/25 04:14:03 2022/09/25
【摘要】 项目中遇到需要连接多个数据库,本来使用SpringBoot默认配置连接是非常简单的,但是由于涉及多个数据库,不得不再自定义配置了,一次性整明白,下次就之间copy使用。 1.首先学习一个注解@...

项目中遇到需要连接多个数据库,本来使用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;//心跳

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 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);
        }
    }
  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 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);
        }
    }


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85

参考地址
代码地址

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

文章来源: springlearn.blog.csdn.net,作者:西魏陶渊明,版权归原作者所有,如需转载,请联系作者。

原文链接:springlearn.blog.csdn.net/article/details/77584879

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。