Spring Boot 解决同名类导致的bean名冲突:

问题描述

项目中有两个同名类都叫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 {
}