admin 管理员组文章数量: 1086864
Spring Boot 解决同名类导致的bean名冲突bean name conflicts
问题描述
项目中有两个同名类都叫MyService,只是放在不同的包名下
package com.yeyuanxinyi;
@Service()
public class MyService {}
package com.yeyuanxiner;
@Service()
public class MyService {}
当项目启动的时候会报如下错误
Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'MyService' for bean class [com.yeyuanxinyi.MyService] conflicts with existing, non-compatible bean definition of same name and class [com.yeyuanxiner.MyService]at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.checkCandidate(ClassPathBeanDefinitionScanner.java:348)at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:286)at org.springframework.context.annotation.ComponentScanAnnotationParser.parse(ComponentScanAnnotationParser.java:132)at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:287)at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:242)at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:199)at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:167)... 13 common frames omitted
解决方法
问题分析:
由于以上两个同名类在用@Service注解的时候未指定value值,所以Spring Boot默认会以类名作为bean name,由于两个类名相同导致了bean name相同的冲突
可以通过为同名类指定不同的bean name来解决问题,上面两个同名类修改后如下
再次运行项目就不会报错了
package com.yeyuanxinyi;
@Service("MyService1")
public class MyService {}
package com.yeyuanxiner;
@Service("MyService2")
public class MyService {}
同理,以上解决方法也适用于@Component
package com.yeyuanxiner;
@Component("MyComponent1")
public class MyComponent {}
本文标签: Spring Boot 解决同名类导致的bean名冲突bean name conflicts
版权声明:本文标题:Spring Boot 解决同名类导致的bean名冲突bean name conflicts 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/b/1687277125a84140.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论