Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring bean alias usage

Tags:

java

spring

I know what bean alias means in spring. But I want to know the use cases for making use of alias. Why would somebody want to refer a bean using alias name instead of its name?

Thanks in advance.

like image 981
Newbie Avatar asked Nov 04 '12 17:11

Newbie


People also ask

Is it possible to assign aliases to a Spring bean?

Sometimes we have use cases that require different codes to reference the same bean using other names or aliases. Fortunately, we can have one bean and give them multiple aliases in Spring.

How do you define bean alias?

...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. One example I can think of if the bean you want to alias is imported from another context XML which you can't or don't want to edit.

What is @bean annotation used for?

Spring @Bean Annotation is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. In this case, bean methods may reference other @Bean methods in the same class by calling them directly.

Can a bean be defined without id or name?

You are not required to supply a name or id for a bean. If no name or id is supplied explicitly, the container generates a unique name for that bean. However, if you want to refer to that bean by name, through the use of the ref element or Service Locator style lookup, you must provide a name.


1 Answers

A usage I've seen is the following: you have two instances of a given interface (SomeBean): one for environment A, and one for environment B. So you define two beans: one named "someBeanForA", and the other one named "someBeanForB".

The beans where this SomeBean must be injected don't know which one they must use: it depends on the environment. So they use an alias:

@Autowired
@Qualifier("someBeanAlias")
private SomeBean someBean;

When deploying to the environment A, the alias in the XML file points to someBeanA. When deploying to the environment B, the alias in the XML file points to someBeanB.

like image 183
JB Nizet Avatar answered Oct 11 '22 22:10

JB Nizet