Is there any difference between using an id
attribute and name
attribute on a
element in a Spring configuration file?
let me answer below question
Is there any difference between using an id attribute and using a name attribute on a
tag,
There is no difference. you will experience same effect when id or name is used on a
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
Let me explain it through an example :
Take this configuration file, let's call it as spring1.xml
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,
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
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
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