最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot mybatis調(diào)用多個(gè)數(shù)據(jù)源引發(fā)的錯(cuò)誤問題

 更新時(shí)間:2022年01月14日 10:23:56   作者:如是雨林  
這篇文章主要介紹了springboot mybatis調(diào)用多個(gè)數(shù)據(jù)源引發(fā)的錯(cuò)誤問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

springboot mybatis調(diào)用多個(gè)數(shù)據(jù)源錯(cuò)誤

報(bào)錯(cuò)

'org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker': Invocation of init method failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: more than one 'primary' bean found among candidates: [mssqlDataSource, postgreDataSource]

從后往前復(fù)制的,加粗的是重點(diǎn)。

因?yàn)橛卸鄠€(gè)數(shù)據(jù)源使用同一個(gè)mapper接口,但是都用@Primary,則會(huì)引起此錯(cuò)誤。

如圖所示:

從上面兩圖可以看出都用了同一個(gè)mapper接口,都添加了@Primary。

解決方法

解決方法有兩種,一種是把其中一個(gè)數(shù)據(jù)源去掉@Primary,動(dòng)態(tài)調(diào)用數(shù)據(jù)源,就是需要代碼切換使用的數(shù)據(jù)源。

如果要同時(shí)使用兩個(gè)數(shù)據(jù)源,那就用不同的mapper,相當(dāng)于postgre用postgre部分的mapper,sqlserver用sqlserver部分的mapper,大家互不干擾,就算@primary也沒事

如圖所示,我將postgre的MapperScan改了

springboot-mybatis多數(shù)據(jù)源及踩坑

springboot項(xiàng)目結(jié)構(gòu)如下

springboot配置文件內(nèi)容如下

動(dòng)態(tài)數(shù)據(jù)源的配置類如下

(必須保證能被ComponentScan掃描到):

package com.letzgo.config;

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.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
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;

/**
 * @author allen
 * @date 2019-01-10 15:08
 */
public class DynamicDatasourceConfig {

    @Configuration
    @MapperScan(basePackages = "com.letzgo.dao.master")
    public static class Master {
        @Primary
        @Bean("masterDataSource")
        @Qualifier("masterDataSource")
        @ConfigurationProperties(prefix = "spring.datasource.master")
        public DataSource dataSource() {
            return new DruidDataSource();
        }

        @Primary
        @Bean("masterSqlSessionFactory")
        @Qualifier("masterSqlSessionFactory")
        public SqlSessionFactory sqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
            factoryBean.setDataSource(dataSource);
            factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/master/*.xml"));
            return factoryBean.getObject();
        }

        @Primary
        @Bean("masterTransactionManager")
        @Qualifier("masterTransactionManager")
        public DataSourceTransactionManager transactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Primary
        @Bean("masterSqlSessionTemplate")
        @Qualifier("masterSqlSessionTemplate")
        public SqlSessionTemplate sqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
            return new SqlSessionTemplate(sqlSessionFactory);
        }

    }

    @Configuration
    @MapperScan(basePackages = "com.letzgo.dao.slave")
    public static class Slave {
        @Bean("slaveDataSource")
        @Qualifier("slaveDataSource")
        @ConfigurationProperties(prefix = "spring.datasource.slave")
        public DataSource dataSource() {
            return new DruidDataSource();
        }

        @Bean("slaveSqlSessionFactory")
        @Qualifier("slaveSqlSessionFactory")
        public SqlSessionFactory sqlSessionFactory(@Qualifier("slaveDataSource") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
            factoryBean.setDataSource(dataSource);
            factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/slave/*.xml"));
            return factoryBean.getObject();
        }

        @Bean("slaveTransactionManager")
        @Qualifier("slaveTransactionManager")
        public DataSourceTransactionManager transactionManager(@Qualifier("slaveDataSource") DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean("slaveSqlSessionTemplate")
        @Qualifier("slaveSqlSessionTemplate")
        public SqlSessionTemplate sqlSessionTemplate(@Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    }

}

完成基本配置之后,分別在master和slave中寫一個(gè)數(shù)據(jù)庫訪問操作,再開放兩個(gè)簡單的接口,分別觸發(fā)master和slave的數(shù)據(jù)看訪問操作。

至此沒項(xiàng)目基本結(jié)構(gòu)搭建已完成,啟動(dòng)項(xiàng)目,進(jìn)行測試。

我們會(huì)發(fā)現(xiàn)這樣master的數(shù)據(jù)庫訪問是能正常訪問的,但是slave的數(shù)據(jù)庫操作是不行的,報(bào)錯(cuò)信息如下:

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):***

對(duì)于這樣錯(cuò)誤,起初企圖通過百度解決,大部分都是說xml文件的命名空間和dao接口全名不對(duì)應(yīng)或者說是接口方法和xml中的方法不對(duì)應(yīng)等等解決方法,

本人檢查了自己的代碼多遍重啟多遍均無法解決,并不是說這些方法不對(duì),但是本案例的問題卻不是這些問題導(dǎo)致的。最后無奈,只能硬著頭皮去看源碼,最后發(fā)現(xiàn)了問題所在。

debug源碼調(diào)試到最后,發(fā)現(xiàn)不論是執(zhí)行mater還是slave的數(shù)據(jù)庫操作,使用了相同的SqlSession,同一個(gè)?。?!這個(gè)肯定是有問題的。

繼續(xù)看源碼進(jìn)行查,看SqlSession的注入過程。

我們知道m(xù)ybatis只要寫接口不用寫實(shí)現(xiàn)類(應(yīng)該是3.0之后的版本),實(shí)際上是使用了代理,每個(gè)dao接口,在spring容器中其實(shí)是對(duì)應(yīng)一個(gè)MapperFactoryBean(不懂FactoryBean的可以去多看看spring的一些核心接口,要想看懂spring源碼必須要知道的)。

當(dāng)從容器中獲取bean的時(shí)候,MapperFactoryBean的getObject方法就會(huì)根據(jù)SqlSession實(shí)例生產(chǎn)一個(gè)MapperProxy對(duì)象的代理類。

問題的關(guān)鍵就在于MapperFactoryBean,他繼承了SqlSessionDaoSupport類,他有一個(gè)屬性,就是SqlSession,而且剛才所說的創(chuàng)建代理類所依賴的SqlSession實(shí)例就是這個(gè)。那我們看這個(gè)SqlSession實(shí)例是什么時(shí)候注入的就可以了,就能找到為什么注入了同一個(gè)對(duì)象了。

找spring注入的地方,spring注入的方式個(gè)人目前知道的有注解處理器如@Autowired的注解處理器AutowiredAnnotationBeanPostProcessor等類似的BeanPostProcessor接口的實(shí)現(xiàn)類,還有一種就是在BeanDefinition中定義器屬性的注入方式,在bean的定義階段就決定了的,前者如果不知道的可以看看,在此不做贅述,后者的處理過程源碼如下(只截取核心部分,感興趣的可以自己看一下處理過程,調(diào)用鏈比較深,貼代碼會(huì)比較多,看著眼花繚亂):

debug到dao接口類的的BeanDefinition(上文已說過其實(shí)是MapperFactoryBean),發(fā)現(xiàn)他的autowiremode是2,參照源碼

即可發(fā)現(xiàn)為按照類型自動(dòng)裝配

最關(guān)鍵的來了

debug的時(shí)候發(fā)現(xiàn),master的dao接口執(zhí)行到this.autowireByType(beanName, mbd, bw, newPvs)方法中,給MapperFactoryBean中SqlSession屬性注入的實(shí)例是masterSqlSessionTemplate對(duì)象,

slave的dao接口執(zhí)行該方法時(shí)注入的也是masterSqlSessionTemplate對(duì)象,按類型注入,spring容器中找到一個(gè)即注入(此時(shí)slaveSqlSessionTemplate也在容器中,為什么按類型注入找到了masterSqlSessionTemplate卻沒報(bào)錯(cuò),應(yīng)該是@Primary的作用)

至此,問題產(chǎn)生的原因已基本找到,那該如何解決呢?BeanDefinition為什么會(huì)定義成autowiremode=2呢,只能找@MapperScan看了,看這個(gè)注解的處理源碼,最后找到ClassPathMapperScanner以下方法:

private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
        Iterator var3 = beanDefinitions.iterator();

        while(var3.hasNext()) {
            BeanDefinitionHolder holder = (BeanDefinitionHolder)var3.next();
            GenericBeanDefinition definition = (GenericBeanDefinition)holder.getBeanDefinition();
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName() + "' and '" + definition.getBeanClassName() + "' mapperInterface");
            }

            definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName());
            definition.setBeanClass(this.mapperFactoryBean.getClass());
            definition.getPropertyValues().add("addToConfig", this.addToConfig);
            boolean explicitFactoryUsed = false;
            if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {
                definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(this.sqlSessionFactoryBeanName));
                explicitFactoryUsed = true;
            } else if (this.sqlSessionFactory != null) {
                definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory);
                explicitFactoryUsed = true;
            }

            if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {
                if (explicitFactoryUsed) {
                    this.logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
                }

                definition.getPropertyValues().add("sqlSessionTemplate", new RuntimeBeanReference(this.sqlSessionTemplateBeanName));
                explicitFactoryUsed = true;
            } else if (this.sqlSessionTemplate != null) {
                if (explicitFactoryUsed) {
                    this.logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
                }

                definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate);
                explicitFactoryUsed = true;
            }

            if (!explicitFactoryUsed) {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");
                }

                definition.setAutowireMode(2);
            }
        }

    }

44行是關(guān)鍵,但是有個(gè)條件,這個(gè)條件成立的原因就是@MapperScan注解沒有指定過sqlSessionTemplateRef或者sqlSessionFactoryRef,正因?yàn)闆]有指定特定的sqlSessionTemplate或者sqlSessionFactory,mybatis默認(rèn)采用按類型自動(dòng)裝配的方式進(jìn)行注入。

至此,問題解決方案已出:

代碼中的兩個(gè)@MapperScan用法分別改為:

@MapperScan(basePackages = "com.letzgo.dao.master", sqlSessionFactoryRef = "masterSqlSessionFactory", sqlSessionTemplateRef = "masterSqlSessionTemplate")??
@MapperScan(basePackages = "com.letzgo.dao.slave", sqlSessionFactoryRef = "slaveSqlSessionFactory", sqlSessionTemplateRef = "slaveSqlSessionTemplate")

重啟進(jìn)行測試,問題解決。

PS:

還是對(duì)各種注解使用方法不了解(或者說對(duì)框架的源碼不了解),導(dǎo)致搞了這么久的問題,還好最后查到了,記錄于此,給自己加深印象,以后還是要多看源碼。以上僅為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Spring?Boot如何通過Actuator顯示git和build的信息

    Spring?Boot如何通過Actuator顯示git和build的信息

    這篇文章主要介紹了Spring?Boot通過Actuator顯示git和build的信息,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-01-01
  • Spring?Security中的CORS詳解

    Spring?Security中的CORS詳解

    CORS(Cross-Origin?Resource?Sharing)是一種允許不同源之間進(jìn)行資源共享的W3C標(biāo)準(zhǔn),它通過在服務(wù)器端設(shè)置特定的HTTP響應(yīng)頭,實(shí)現(xiàn)了跨域請(qǐng)求的功能,這種機(jī)制要求瀏覽器和服務(wù)器的支持,本文給大家介紹Spring?Security中的CORS,感興趣的朋友一起看看吧
    2024-10-10
  • Java中indexOf函數(shù)示例詳解

    Java中indexOf函數(shù)示例詳解

    Java String 類的 indexOf() 方法返回指定字符串中指定字符或字符串第一次出現(xiàn)的位置,這篇文章主要介紹了Java中indexOf函數(shù)詳解,需要的朋友可以參考下
    2024-01-01
  • Java實(shí)現(xiàn)快速冪算法詳解

    Java實(shí)現(xiàn)快速冪算法詳解

    快速冪是用來解決求冪運(yùn)算的高效方式。此算法偶爾會(huì)出現(xiàn)在筆試以及面試中,特意花時(shí)間研究了下這題,感興趣的小伙伴快跟隨小編一起學(xué)習(xí)一下
    2022-10-10
  • Java實(shí)現(xiàn)幾種序列化方式總結(jié)

    Java實(shí)現(xiàn)幾種序列化方式總結(jié)

    本篇文章主要介紹了Java實(shí)現(xiàn)幾種序列化方式總結(jié),包括Java原生以流的方法進(jìn)行的序列化、Json序列化、FastJson序列化、Protobuff序列化,有興趣的可以了解一下,
    2017-03-03
  • log4j2使用filter過濾日志方式

    log4j2使用filter過濾日志方式

    這篇文章主要介紹了log4j2使用filter過濾日志方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Java中遍歷集合的并發(fā)修改異常解決方案實(shí)例代碼

    Java中遍歷集合的并發(fā)修改異常解決方案實(shí)例代碼

    當(dāng)你遍歷集合的同時(shí),又往集合中添加或者刪除元素,就可能報(bào)并發(fā)修改異常,下面這篇文章主要給大家介紹了關(guān)于Java中遍歷集合的并發(fā)修改異常解決方案的相關(guān)資料,需要的朋友可以參考下
    2022-12-12
  • HttpClient 請(qǐng)求 URL字符集轉(zhuǎn)碼問題

    HttpClient 請(qǐng)求 URL字符集轉(zhuǎn)碼問題

    這篇文章主要介紹了HttpClient 請(qǐng)求 URL字符集轉(zhuǎn)碼問題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-01-01
  • spring cloud 之 Feign 使用HTTP請(qǐng)求遠(yuǎn)程服務(wù)的實(shí)現(xiàn)方法

    spring cloud 之 Feign 使用HTTP請(qǐng)求遠(yuǎn)程服務(wù)的實(shí)現(xiàn)方法

    下面小編就為大家?guī)硪黄猻pring cloud 之 Feign 使用HTTP請(qǐng)求遠(yuǎn)程服務(wù)的實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-06-06
  • IDEA+Maven打JAR包的兩種方法步驟詳解

    IDEA+Maven打JAR包的兩種方法步驟詳解

    Idea中為一般的非Web項(xiàng)目打Jar包是有自己的方法的,下面這篇文章主要給大家介紹了關(guān)于IDEA+Maven打JAR包的兩種方法,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-09-09

最新評(píng)論

涿州市| 苗栗县| 高平市| 青铜峡市| 大城县| 内丘县| 扬州市| 乌兰浩特市| 安塞县| 华阴市| 三河市| 丽江市| 黎城县| 扬中市| 德安县| 南皮县| 烟台市| 吐鲁番市| 清新县| 西和县| 高平市| 林甸县| 昌吉市| 莆田市| 桃园县| 沈阳市| 海晏县| 长寿区| 台江县| 东阳市| 寿光市| 葫芦岛市| 长泰县| 甘肃省| 泾川县| 泽库县| 江门市| 定兴县| 澄迈县| 辽阳县| 平远县|