Java, Software Development, Spring

Spring – Multiple names for a bean

This post shows how to assign multiple names or aliases to a bean in Spring.

Item We Used

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

Bean Name Aliasing

Spring allows a bean to have multiple names.

Using XML Configuration

In XML, we can achieve aliasing by specifying a space-, comma, or semi-colon delimited string of names in the name attribute of the bean’s <bean> tag.

 

For example:

We can also use the <alias> tag.

Referencing Aliases

We can now reference the same bean using different aliases.

Output

Please download the codes here.

Using Java Configuration

In Java configuration, we can achieve aliasing by using an array of names as a parameter to the @Bean’s name attribute.

Output

Please download the codes here.

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.