0

Spring – Multiple names for a bean

This post demonstrates how to assign multiple names (or aliases) to a bean.

Stuff 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

Download Codes

https://github.com/Turreta/Spring-Multiple-names-for-a-bean-xml-config

Using Java Configuration

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

Output

Download Codes

https://github.com/Turreta/Spring-Multiple-names-for-a-bean-java-config

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert