今天做springboot+dubbo+zookeeper服务注册与发现,出现一个问题,工程老是起不来,日志如下:
2019-12-10 16:29:37.766 WARN 72124 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to register bean definition with name 'userService'
Offending resource: class path resource [dubbo.xml]; nested exception is org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'userService' defined in class path resource [dubbo.xml]: Cannot register bean definition [Generic bean: class [com.stm.demo.dubbo.provicderandconsumer.service.UserServiceImpl]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [dubbo.xml]] for bean 'userService': There is already [Root bean: class [com.alibaba.dubbo.config.spring.ReferenceBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] bound.
2019-12-10 16:29:37.794 INFO 72124 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-12-10 16:29:37.798 ERROR 72124 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
The bean 'userService', defined in class path resource [dubbo.xml], could not be registered. A bean with that name has already been defined in null and overriding is disabled.
Action:
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
问题描述:项目无法启动,日志描述为:无法注册在类路径资源[dubbo.xml]中定义的bean“userService”。已在null中定义了具有该名称的bean,并且已禁用重写。
解决过程:我用springboot版本是 2.1.2.RELEASE,出现这个问题,后来把springboot版本换成 2.0.4.RELEASE,问题消失。
如果不更换springboot版本,在application.properties配置文件中添加spring.main.allow-bean-definition-overriding=true,问题消失。
原因分析:springboot2.0.X.RELEASE中用到的资源没有和userService重名的bean,而 2.1.X.RELEASE中有用到资源有与userService重名的bean。
解决方法:方案1、更换springboot版本,把springboot版本换成2.0.X
方案2、在application.properties配置文件中添加spring.main.allow-bean-definition-overriding=true,表示后发现的bean会覆盖之前相同名称的bean
备注:关于allowBeanDefinitionOverriding的配置,spring中默认是true,默认支持名称相同的bean的覆盖。而springboot中的默认值是false,不支持名称相同的bean被覆盖。springboot对这个参数进行了二次封装,springboot中的allowBeanDefinitionOverriding没有初始化默认值,java中的boolean类型不初始化时是false。