Correctness35 - SpotBugsExtensionForSpringFrameWork/CS5098 GitHub Wiki
This will be moved since link is relevant bug pattern
Bug pattern name: If multiple beans of the same type without an ID or name are declared, Spring will throw an exception
"Spring supports quite a complex bean-naming structure that allows you the flexibility to handle many situations. Every bean must have at least one name that is unique within the containing ApplicationContext. Spring follows a simple resolution process to determine what name is used for the bean. If you give the tag an id attribute, the value of that attribute is used as the name. If no id attribute is specified, Spring looks for a name attribute, and if one is defined, it uses the first name defined in the name attribute. If neither the id nor the name attribute is specified, Spring uses the bean’s class name as the name, provided, of course, that no other bean is using the same class name. If multiple beans of the same type without an ID or name are declared, Spring will throw an exception (NoSuchBeanDefinitionException) on injection during ApplicationContext initialization." In summary, if there is no name and id when looking for a bean in a definition file, the class name (type) is set as the bean name, but if the same class (type) exists, Spring does not know which one to choose.
"If multiple beans of the same type without an ID or name are declared, Spring will throw an exception (of type org.springframework.beans.factory.NoSuchBeanDefinitionException) on injection during ApplicationContext initialization."
<beans ...>
<bean id="string1" class="java.lang.String"/>
<bean name="string2" class="java.lang.String"/>
<bean class="java.lang.String"/> // avoid this
<bean class="java.lang.String"/> // avoid this
</beans>
Be careful - we cannot alert in the case that the same type is defined in XML configuration file, since the id could be defined in annotation like below.
@Component("anyBeanName")
public class HelloBean{
}
Another be careful - in the case of @Profile code, the bean ID can be the same, as the properties file can help Spring with recognition of active bean.
// Code from GURU Spring Framework
@Service("i18nService")
@Profile("EN")
class EnglishGreetingService implement GreetingService{}
// ------------------------------------------
@Service("i18nService")
@Profile("DE")
class GermanGreetingService implement GreetingService{}
// ------------------------------------------
// property file
spring.profiles.active = EN
// ------------------------------------------
// Default can be used
@Service("i18nService")
@Profile({"EN", "default"})
class EnglishGreetingService implement GreetingService{}
"As a general practice, you should give your bean a name by using the id attribute and then associate the bean with other names by using name aliasing,"
<beans ...>
<bean id="john" name="john johnny,jonathan;jim" class="java.lang.String"/>
<alias name="john" alias="ion"/>
</beans>
Pro Spring 5 (95 page)