多数据源配置时出现的一些问题

自己写了一个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注解。

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