当我在Spring Web应用程序中加载网页时,出现以下错误:
java.lang.IllegalStateException: More than one bean of type [com.Car] found, you have to specify the name of the bean
如何在启动时强制Spring检测此问题?
请注意我知道如何自行解决问题(例如删除两个定义中的一个) 我只是想确保在打开每个网页之前没有其他任何我无法找到的案例。
答案 0 :(得分:1)
创建一个BeanPostProcessor,它跟踪在应用程序上下文中为每个bean定义创建的实例数。这将为您想要限制的bean类型抛出异常,并将暂停容器初始化。因此,您可以提前检测到错误
public class DuplicateBeanDetectionBeanPostProcessor implements BeanPostProcessor{
private Map<Class<?> , Boolean> beanTypeFound = new HashMap<Class<?> , Boolean>();
private Set<Class<?> typesToRestrictToOneInstance = new HashSet<Class<?>>();
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException{
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException{
Set<Class<?>> restrictedTypesForBean = findRestrictedTypesForInstance(bean);
if(!restrictedTypeForBean.isEmpty() && typeAlreadyFound(bean , restrictedTypesForBean)){
throw new IllegalStateException("Bean of type : " + restrictedTypeForBean + " already found in the application context";
}
return bean;
}
private Set<Class<?>> findRestrictedTypesForInstance(Object bean){
Set<Class<?>> restrictedTypesForBean = hew HashSet<>();
Class<?> superClass = bean.getClass();
while(superClass != null){
for(Class<?> restrictedType : typesToRestrictToOneInstance){
if(restrictedType.isAssignableFrom(superClass){
restrictedTypesForBean.add(restrictedType);
}
}
}
return restrictedTypesForBean;
}
private boolean typeAlreadyFound(Object bean , Set<Class<?>> restrictedTypesForBean){
for(Class<?> restrictedTypeForBean : restrictedTypesForBean){
if(beanTypeFound.get(restrictedTypeForBean)){
return true;
}
else{
beanTypeFound.set(restrictedTypeForBean , true);
}
}
return false;
}
public void setTypesToRestrictToOneInstance(Set<Class<?>> typesToRestrictToOneInstance){
this.typesToRestrictToOneInstance = typesToRestrictToOneInstance;
}
}
通过适合您的配置机制将BeanPostProcessor添加到您的应用程序上下文中。然后设置要限制的所有类型