Java, Software Development, Spring

Spring – Multiple Names Or Aliases For A Bean

Spring Multiple name alias bean ApplicationContext JUnit Tests Spring Boot Security PreAuth

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? Please visit our Facebook page!

You Might Also Like

2 Comments

  1. 1

    what happens if the bean already exists? for instance say I want to do:

    but “foo” already exists elsewhere.
    Should I do?

    @Bean(“bar”)
    public Object bar(@Qualifier(“foo”) Object foo) {
    return foo;
    }

    the only other way I could see to do this is to implement a BeanPostProcessor and call the registerAlias method, but then I’m stuck not being able to reference “bar” within this Configuration.

  2. 2

    I think that is fine as long as it refers to the same object. You could create a separate Configuration class just for aliasing stuff like this.

Comments are closed.