Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - usage of alias vs names

Tags:

spring

I am confused on the usage of alias. I do understand what alias is and how it is being used but i don't see how it can be any different than using names on a bean definition.

<bean id="xyx" name="abc,def" .. />  <alias name="xyx" alias="pqr"/> 

Why the alias when i can use abc or def?

like image 341
yapkm01 Avatar asked Mar 04 '13 21:03

yapkm01


People also ask

Why do we use alias in Spring?

Bean aliasing allows us to override already configured beans and to substitute them with a different object definition. This is most useful when the bean definitions are inherited from an external resource, which is out of our control.

Can a bean have multiple names?

8. A bean can have more than one name using multiple id attributes? Explanation: Beans are allowed to have more than one ids.

Can a bean be given multiple names via alias tag?

Even before the advent of Java configurations, Spring allows a bean to have multiple names using XML configurations. In fact, we can give a bean multiple names by using the name attribute of the bean element.

How do you give an alias name to a bean in Spring?

Spring <alias> element defines an alias for a bean in XML configuration. The <alias> element can be used to alias a bean outside the bean definition. The <alias> is useful in the large applications where configurations are split amongst each subsystem and each subsystem is having its own bean definitions.


2 Answers

In my mind bean aliasing can be helpful in large system, where you can not manipulate bean names. You have option to create your own name (alias) specific for your part of the system...

from Spring documentation (3.0.x) http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/htmlsingle/

...it is sometimes desirable to give a single bean multiple names, otherwise known as bean aliasing...

therefore creating multiple names or/and aliasing are the same thing.

like image 94
Marcin Wasiluk Avatar answered Sep 21 '22 20:09

Marcin Wasiluk


A use case maybe when you want to customize some beans that are already defined somewhere in a modular application (each module is a spring project for example), the bean maybe defined by a third-party framework/API or even your team. In that case you want that only inside your spring project call the customized version without altering other modules (projects), to do that just add the alias in your spring configuration which is indeed a powerful feature:

<alias alias="globalBeanService" name="customizedBeanService" /> 

Hence, whenever spring find a call to the globalBeanService, it will inject customizedBeanService for you inside your specific module. Without this feature, you should go through all classes and modify the bean manually!!

like image 32
Adil Avatar answered Sep 20 '22 20:09

Adil