let me answer below question
Is there any difference between using an id attribute and using a name attribute on a <bean> tag,
There is no difference. you will experience same effect when id or name is used on a <bean> tag .
How?
Both id and name attributes are giving us a means to provide identifier value to a bean (For this moment, think id means id but not identifier). In both the cases, you will see same result if you call applicationContext.getBean("bean-identifier");
.
Take @Bean, the java equivalent of <bean> tag, you wont find an id attribute. you can give your identifier value to @Bean only through name attribute.
Let me explain it through an example :
Take this configuration file, let's call it as spring1.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<bean id="foo" class="com.intertech.Foo"></bean>
<bean id="bar" class="com.intertech.Bar"></bean>
</beans>
Spring returns Foo object for, Foo f = (Foo) context.getBean("foo");
. Replace id="foo"
with name="foo"
in the above spring1.xml, You will still see the same result.
Define your xml configuration like,
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<bean id="fooIdentifier" class="com.intertech.Foo"></bean>
<bean name="fooIdentifier" class="com.intertech.Foo"></bean>
</beans>
You will get BeanDefinitionParsingException. It will say, Bean name 'fooIdentifier' is already used in this element. By the way, This is the same exception you will see if you have below config
<bean name="fooIdentifier" class="com.intertech.Foo"></bean>
<bean name="fooIdentifier" class="com.intertech.Foo"></bean>
If you keep both id and name to the bean tag, the bean is said to have 2 identifiers. you can get the same bean with any identifier.
take config as
<?xml version="1.0" encoding="UTF-8"?><br>
<beans ...>
<bean id="fooById" name="fooByName" class="com.intertech.Foo"></bean>
<bean id="bar" class="com.intertech.Bar"></bean>
</beans>
the following code prints true
FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(...);
Foo fooById = (Foo) context.getBean("fooById")// returns Foo object;
Foo fooByName = (Foo) context.getBean("fooByName")// returns Foo object;
System.out.println(fooById == fooByName) //true