问题起因:
开发过程中更新代码 就报错了(整个项目运行不起来)。
报错信息如下:
Annotation-specified bean name 'fileUploadDispatcher' for bean class [com.echo.test.FileUploadDispatcher] conflicts with existing, non-compatible bean definition of same name and class [com.echo.util.FileUploadDispatcher]
原因:
在项目中 不同路径下 存在相同的组件名。
原理:
在加载bean的时候 默认有个校验机制,SpringMVC中bean的加载 是采用类似 键值对(key/value)的映射方式存储的,而当中的(key)键,默认是用类名来作为键的(如果不取别名的话)。这样 如果不同包路径下的 两个组件(controller/service)重名的话 就会触发这个校验机制,抛异常。
源代码如下:
protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition) throws IllegalStateException {
if (!this.registry.containsBeanDefinition(beanName)) {
return true;
}
BeanDefinition existingDef = this.registry.getBeanDefinition(beanName);
BeanDefinition originatingDef = existingDef.getOriginatingBeanDefinition();
if (originatingDef != null) {
existingDef = originatingDef;
}
if (isCompatible(beanDefinition, existingDef)) {
return false;
}
throw new ConflictingBeanDefinitionException("Annotation-specified bean name '" + beanName +
"' for bean class [" + beanDefinition.getBeanClassName() + "] conflicts with existing, " +
"non-compatible bean definition of same name and class [" + existingDef.getBeanClassName() + "]");
}
if (!this.registry.containsBeanDefinition(beanName)) {
return true;
}
BeanDefinition existingDef = this.registry.getBeanDefinition(beanName);
BeanDefinition originatingDef = existingDef.getOriginatingBeanDefinition();
if (originatingDef != null) {
existingDef = originatingDef;
}
if (isCompatible(beanDefinition, existingDef)) {
return false;
}
throw new ConflictingBeanDefinitionException("Annotation-specified bean name '" + beanName +
"' for bean class [" + beanDefinition.getBeanClassName() + "] conflicts with existing, " +
"non-compatible bean definition of same name and class [" + existingDef.getBeanClassName() + "]");
}
解决方案:
取别名。
例如
@Component("FileUploadDispatcherDemo")
public class FileUploadDispatcher {}
public class FileUploadDispatcher {}
同理,对于 Controller/service/dao 都一样