多數據源配置時出現的一些問題

自己寫了一個SpringBoot結構的小項目,練習一下多數據源的配置。因爲是從之前的項目中拷貝的代碼,不清楚其實現原理,因此出現了一些錯誤。

一、Premature end of file.

控制檯輸出如下:

Caused by: org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [E:\githubproject\rong_system\target\classes\mapping\rong\boke\read\BokeDisplayWorksReadMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error creating document instance.  Cause: org.xml.sax.SAXParseException; Premature end of file.

按照字面意思是“文件提前結束”,問題出現在這個BokeDisplayWorksReadMapper.xml。網上說原因是因爲有沒有正確結束的標籤。但是所有的基礎代碼都是用generator插件自動生成的,沒做任何改動,不會出現語法錯誤。分析一下,原來是因爲我註釋掉了這個文件。當時爲了解決其他錯誤,縮小排查範圍,直接註釋掉了整個mapper.xml文件。springBoot 掃描的時候,能掃描到文件名,但是文件內容是空白的,因此直接報錯。

二、more than one 'primary' bean found among candidates

控制檯輸出如下:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'systemReadDataSource' defined in class path resource [com/byk/rong/system/config/SystemReadDataSourceConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceInitializer': Invocation of init method failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] is defined: more than one 'primary' bean found among candidates: [bokeWriteDataSource, bokeReadDataSource, systemWriteDataSource, systemReadDataSource]

很明顯,出現了不止一個的“primary”,找出primary出現的位置。一共有四個數據源配置文件在其中兩個文件中用到了

@Primary註解,試着刪掉其中一個文件中的@Primary註解,項目正常啓動。

三、required a single bean, but 4 were found

問題二里面刪掉了一個@Primary項目能啓動,那要是刪除所有的@Primary註解呢。

控制檯輸出如下:

Description:

Parameter 0 of method sqlSessionFactory in com.byk.rong.system.config.SystemReadDataSourceConfiguration required a single bean, but 4 were found:
    - bokeWriteDataSource: defined by method 'dataSource' in class path resource [com/byk/rong/boke/config/BokeWriteDataSourceConfiguration.class]
    - bokeReadDataSource: defined by method 'dataSource' in class path resource [com/byk/rong/boke/config/BokeReadDataSourceConfiguration.class]
    - systemWriteDataSource: defined by method 'dataSource' in class path resource [com/byk/rong/system/config/SystemWriteDataSourceConfiguration.class]
    - systemReadDataSource: defined by method 'dataSource' in class path resource [com/byk/rong/system/config/SystemReadDataSourceConfiguration.class]


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
字面意思“要求有一個單獨的bean ,但是找到了四個”,就是說springboot已經分不清需啓動時需要加載哪個bean了。最下面也給出了修改意見,加一@Primary或者@Qualifier註解。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章