diff --git a/org.springframework.context/src/main/java/org/springframework/context/annotation/AnnotationBeanNameGenerator.java b/org.springframework.context/src/main/java/org/springframework/context/annotation/AnnotationBeanNameGenerator.java index f0780a8fe23..515aa2e7172 100644 --- a/org.springframework.context/src/main/java/org/springframework/context/annotation/AnnotationBeanNameGenerator.java +++ b/org.springframework.context/src/main/java/org/springframework/context/annotation/AnnotationBeanNameGenerator.java @@ -20,6 +20,7 @@ import java.beans.Introspector; import java.util.Map; import java.util.Set; +import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionRegistry; @@ -73,7 +74,7 @@ public class AnnotationBeanNameGenerator implements BeanNameGenerator { } } // Fallback: generate a unique default bean name. - return buildDefaultBeanName(definition); + return buildDefaultBeanName(definition, registry); } /** @@ -119,6 +120,26 @@ public class AnnotationBeanNameGenerator implements BeanNameGenerator { return (isStereotype && attributes != null && attributes.containsKey("value")); } + /** + * Derive a default bean name from the given bean definition. + *

The default implementation delegates to {@link #buildDefaultBeanName(BeanDefinition)}, + * appending a counter suffix if necessary to make the bean name unique in the given registry. + * @param definition the bean definition to build a bean name for + * @param registry the registry that the given bean definition is being registered with + * @return the default bean name (never null) + */ + protected String buildDefaultBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) { + String generatedName = buildDefaultBeanName(definition); + // Increase counter until the id is unique. + String id = generatedName; + int counter = 0; + while (registry.containsBeanDefinition(id)) { + counter++; + id = generatedName + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR + counter; + } + return id; + } + /** * Derive a default bean name from the given bean definition. *

The default implementation simply builds a decapitalized version