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 {

}

 

 

 

 

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值