Java, Software Development, Spring

Spring – Multiple Names Or Aliases For A 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. This post shows how to assign multiple names or aliases to a bean in Spring.

Spring Project Requirements

We use the following items for this post

  • Spring Boot 2.0.6.RELEASE
  • IntelliJ IDEA
  • JDK 8
  • Using Java Configuration

Multiple Names For a Bean Using XML

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. Instead of specifying a single string, we could provide a set of strings delimited by specifying spaces, commas, or semi-colons. Consider the following sample Spring XML configuration.

Notice we defined two beans with different ids – idBean1  and idBean2. We used the name attribute for each bean to specify a list of string values to serve as their respective aliases. Alternatively, we can use the alias tag.

Multiple Names For a Bean Using Java Configuration

Using XML configuration, especially for large projects, is cumbersome and difficult to maintain. Therefore, we are better off starting new projects using Java configuration classes. Nowadays, most greenfield projects, if not all, are using Java configuration classes.  In Java configuration, we can achieve aliasing in Spring by using an array of names as a parameter to the attribute of a bean. Consider the following codes.

Referencing Bean Aliases In Spring

Referencing Spring bean aliases is straightforward using the Autowired annotation. But when we need to reference a bean with a specific name, we could use the Qualifier. Consider the following codes.

When we run the codes, we get the following output.

The sample codes for our Spring with multiple names projects are available from the following links: Spring XML Config and Spring Java Config.

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like