Spring - usage of alias vs names

An aliased bean will always have higher priority over a non-aliased one, and in case of having different beans with the same alias then the last one declared will have the priority. In other words, the aliased bean will override the non-aliased beans. This can be particularly useful when creating big projects or when you are building extensions to your project and don't want to touch the original bean definition.


Alias has a specific using scenario which multiple names don't have:

Imagine multiple config xml files in your project, most of which are authored by your colleagues, and you need to add your own config.xml file. Using you'll be able to refer to a bean defined in another config file with a different name that's maybe more meaningful to your config, without having to touch your colleagues' config files.


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.


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!!

Tags:

Spring