解决The bean ‘dataSource‘, defined in BeanDefinition defined in class path resource 问题

在启动springboot+springcloud项目时遇到错误,bean 'dataSource'注册失败。解决方案是在配置文件中添加`spring.main.allow-bean-definition-overriding=true`,但根本原因是SpringBoot和SpringCloud版本不兼容。降低版本到合适组合可以解决问题,强调技术选型时要考虑组件兼容性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

今天在启动springboot+springcloud项目的时候,发现报一个错误 如下错误

Error starting ApplicationContext. To display the conditions report re-run your application with ‘debug’ enabled.
2020-09-17 16:34:52.056 ERROR 19128 — [ main] o.s.b.d.LoggingFailureAnalysisReporter :


APPLICATION FAILED TO START


Description:

The bean ‘dataSource’, defined in BeanDefinition defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration H i k a r i . c l a s s ] , c o u l d n o t b e r e g i s t e r e d . A b e a n w i t h t h a t n a m e h a s a l r e a d y b e e n d e f i n e d i n c l a s s p a t h r e s o u r c e [ o r g / s p r i n g f r a m e w o r k / b o o t / a u t o c o n f i g u r e / j d b c / D a t a S o u r c e C o n f i g u r a t i o n Hikari.class], could not be registered. A bean with that name has already been defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration Hikari.class],couldnotberegistered.Abeanwiththatnamehasalreadybeendefinedinclasspathresource[org/springframework/boot/autoconfigure/jdbc/DataSourceConfigurationHikari.class] and overriding is disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true

Disconnected from the target VM, address: ‘127.0.0.1:62029’, transport: ‘socket’

Process finished with exit code 1

从错误信息中可以看到,dataSource这个bean已经被register了

解决方案

从下图看:
在这里插入图片描述
只要在配置文件中加入

spring.main.allow-bean-definition-overriding=true

设置为true时,后定义的bean会覆盖之前定义的相同名称的bean,如图
在这里插入图片描述

根本原因分析

我们分析根本原因,发现上面解决方案不是根本原因,终究原因后面发现是SpringBoot和SpringCloud版本匹配问题导致的。

  • 问题前版本号为
<spring-boot.version>2.2.5.RELEASE</spring-boot.version>
<spring-cloud.version>Hoxton.SR3</spring-cloud.version>
  • 解决后版本为
<spring-boot.version>2.0.4.RELEASE</spring-boot.version>
<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>

把版本降下来后,问题自然解决了,这才是推荐方案,从根本上解决

写在最后

所以,我们在技术选型时,不用一味的追求最新的,要考虑到各组件的兼容性,选择最合适的,才是最好的。

最后提醒一下:

spring中默认是true,也就是默认支持名称相同的bean的覆盖。而springboot中的默认值是false,也就是不支持名称相同的bean被覆盖。

如果能帮到您,记得关注一下哈

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值