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.
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.
...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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With