Spring version - 5.3.22
Aliases overwrite the ID property, moreover they are not verifying for presence of duplicate beans. The case remains same with Name.
Please have a look at below code for better understanding.
Bean Definition
<bean id="string_bean" class="java.lang.String">
<constructor-arg value="Sample" />
</bean>
<bean id="string_bean1" class="java.lang.String">
<constructor-arg value="Sample 1" />
</bean>
<alias name="string_bean" alias="string_bean1" />
<alias name="string_bean1" alias="string" />
Java File
ApplicationContext context = new ClassPathXmlApplicationContext("\\config\\basics.xml");
String[] beanNames = {
"string_bean",
"string_bean1",
"string"
};
for(String beanName : beanNames) {
String str = context.getBean(beanName, String.class);
System.out.println("For " + beanName + " => " + str);
}
Output
For string_bean => Sample
For string_bean1 => Sample
For string => Sample
Comment From: sbrannen
I would not suggest defining an alias such as string_bean1
that conflicts with an existing bean ID/name.
Are you expecting Spring to throw an exception if that occurs?
Also, what exactly are you trying to achieve?
Comment From: spring-projects-issues
If you would like us to look at this issue, please provide the requested information. If the information is not provided within the next 7 days this issue will be closed.
Comment From: Abhi4281
If this is the expected behavior then its fine.
However, while handling large amount of configuration details this could possibly lead to a Logical error, which would be very difficult to debug for the users.
Not trying to achieve anything, just learning Spring :)
Comment From: snicoll
Yes it's the expected behavior. Spring Boot has an option to prevent bean overriding by default, which would prevent the use case from happening. On an AbstractRefreshableBeanFactory
you can call setAllowBeanDefinitionOverriding
to disallow bean overriding.