多資料來源配置時出現的一些問題
自己寫了一個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註解。