SpringBoot整合多數(shù)據(jù)源xml方式

項目中遇到需要連接多個數(shù)據(jù)庫嗦锐,本來使用SpringBoot默認配置連接是非常簡單的晌姚,但是由于涉及多個數(shù)據(jù)庫,不得不再自定義配置了痘括,一次性整明白驶兜,下次就之間copy使用。

  • 1.首先學(xué)習(xí)一個注解@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;//最大連接數(shù)
    private int minIdle;//最小連接數(shù)
    private int initialSize;//初始化數(shù)量和
    private boolean testOnBorrow;
    private Long timeBetweenEvictionRunsMillis;//心跳
  • 2.添加數(shù)據(jù)源配置A
    /**
     * @Package: pterosaur.account.config.druid
     * @Description: account 數(shù)據(jù)源1
     * @author: liuxin
     * @date: 17/4/21 下午7:11
     */
    @Configuration
    @EnableConfigurationProperties(DruidProperties.class) //開啟屬性注入,通過@autowired注入 //注入DruidProerties,就是根據(jù)第一個注解,創(chuàng)建的配置類
    @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 是一個接口驰后,因為是兩個數(shù)據(jù)源肆资,所以用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.添加數(shù)據(jù)源配置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 數(shù)據(jù)源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(僅僅在當(dāng)前上下文中存在某個對象時灶芝,才會實例化一個Bean)
@ConditionalOnClass(某個class位于類路徑上郑原,才會實例化一個Bean)
@ConditionalOnExpression(當(dāng)表達式為true的時候唉韭,才會實例化一個Bean)
@ConditionalOnMissingBean(僅僅在當(dāng)前上下文中不存在某個對象時,才會實例化一個Bean)
@ConditionalOnMissingClass(某個class類路徑上不存在的時候犯犁,才會實例化一個Bean)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末属愤,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子酸役,更是在濱河造成了極大的恐慌住诸,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件涣澡,死亡現(xiàn)場離奇詭異贱呐,居然都是意外死亡,警方通過查閱死者的電腦和手機入桂,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進店門奄薇,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人抗愁,你說我怎么就攤上這事馁蒂。” “怎么了蜘腌?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵远搪,是天一觀的道長。 經(jīng)常有香客問我逢捺,道長谁鳍,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任劫瞳,我火速辦了婚禮倘潜,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘志于。我一直安慰自己涮因,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布伺绽。 她就那樣靜靜地躺著养泡,像睡著了一般。 火紅的嫁衣襯著肌膚如雪奈应。 梳的紋絲不亂的頭發(fā)上澜掩,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天,我揣著相機與錄音杖挣,去河邊找鬼肩榕。 笑死,一個胖子當(dāng)著我的面吹牛惩妇,可吹牛的內(nèi)容都是我干的株汉。 我是一名探鬼主播筐乳,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼乔妈!你這毒婦竟也來了蝙云?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤路召,失蹤者是張志新(化名)和其女友劉穎勃刨,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體优训,經(jīng)...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年各聘,在試婚紗的時候發(fā)現(xiàn)自己被綠了揣非。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,696評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡躲因,死狀恐怖早敬,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情大脉,我是刑警寧澤搞监,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站镰矿,受9級特大地震影響琐驴,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜秤标,卻給世界環(huán)境...
    茶點故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一绝淡、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧苍姜,春花似錦牢酵、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至垫释,卻和暖如春丝格,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背棵譬。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工铁追, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人茫船。 一個月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓琅束,卻偏偏與公主長得像扭屁,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子涩禀,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,592評論 2 353

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理料滥,服務(wù)發(fā)現(xiàn),斷路器艾船,智...
    卡卡羅2017閱讀 134,651評論 18 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,803評論 6 342
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法葵腹,類相關(guān)的語法,內(nèi)部類的語法屿岂,繼承相關(guān)的語法践宴,異常的語法,線程的語...
    子非魚_t_閱讀 31,622評論 18 399
  • 文章作者:Tyan博客:noahsnail.com 3.4 Dependencies A typical ente...
    SnailTyan閱讀 4,152評論 2 7
  • 昨晚和表哥一起到外婆家吃飯,老人家?guī)讉€月未見运授,一看到我們回來就廚房客廳忙里忙外烤惊。我給她買了件羊毛衫,穿著合身吁朦,她高...
    卷毛維安閱讀 6,835評論 41 252