Spring多数据源配置问题

在实际项目中,不可避免地会出现多个数据库的配置,记录一下我遇到的问题。

在db.xml文件中配置了dataSource和sqlSessionFactory,其中sqlSessionFactory的一个属性就是该dataSource。

在job.xml中配置了quartz的数据源quartzDataSource。

注意,两个dataSource是同一类型的。

在项目启动时,控制台报错,信息如下:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [config/spring/applicationContext.rms.db.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource';           nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [config/spring/applicationContext.rms.db.xml]: 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' available: expected single matching bean but found 2: dataSource,quartzDataSource

大致意思是说,在创建sqlSessionFactory的属性dataSource的时候报错。dataSource这个bean初始化失败,因为在创建dataSourceInitializer这个初始化bean的时候,找不到唯一的需要注入的bean,而是找到了两个。

查看这个类的源码,部分如下:

可以得知dataSource的注入是根据类型进行匹配的,因此会找到两个bean。
解决方式就是使用bean的primary这个属性,这个属性标识在相同类型的bean中,会优先使用这个bean进行注入。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值