在实际项目中,不可避免地会出现多个数据库的配置,记录一下我遇到的问题。
在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进行注入。