1. Overview
Naming a Spring bean is quite helpful when we have multiple implementations of the same type. This is because itβll be ambiguous to Spring to inject a bean if our beans donβt have unique names.
By having control over naming the beans, we can tell Spring which bean we want to inject into the targeted object.
In this article, weβll discuss Spring bean naming strategies and also explore how we can give multiple names to a single type of bean.
2. Default Bean Naming Strategy
Spring provides multiple annotations for creating beans. We can use these annotations at different levels. For example, we can place some annotations on a bean class and others on a method that creates a bean.
First, letβs see the default naming strategy of Spring in action. How does Spring name our bean when we just specify the annotation without any value?
2.1. Class-Level Annotations
Letβs start with the default naming strategy for an annotation used at the class level. To name a bean, Spring uses the class name and converts the first letter to lowercase.
Letβs take a look at an example:
@Service
public class LoggingService {
}
Here, Spring creates a bean for the class LoggingService and registers it using the name βloggingServiceβ.
This same default naming strategy is applicable for all class-level annotations that are used to create a Spring bean, such as @Component, @Service, and @Controller.
2.2. Method-Level Annotation
Spring provides annotations like @Bean and @Qualifier to be used on methods for bean creation.
Letβs see an example to understand the default naming strategy for the @Bean annotation:
@Configuration
public class AuditConfiguration {
@Bean
public AuditService audit() {
return new AuditService();
}
}
In this configuration class, Spring registers a bean of type AuditService under the name βauditβ because when we use the @Bean annotation on a method, Spring uses the method name as a bean name.
We can also use the @Qualifier annotation on the method, and weβll see an example of it below.
3. Custom Naming of Beans
When we need to create multiple beans of the same type in the same Spring context, we can give custom names to the beans and refer to them using those names.
So, letβs see how can we give a custom name to our Spring bean:
@Component("myBean")
public class MyCustomComponent {
}
This time, Spring will create the bean of type MyCustomComponent with the name βmyBeanβ.
As weβre explicitly giving the name to the bean, Spring will use this name, which can then be used to refer to or access the bean.
Similar to @Component(βmyBeanβ), we can specify the name using other annotations such as @Service(βmyServiceβ), @Controller(βmyControllerβ), and @Bean(βmyCustomBeanβ), and then Spring will register that bean with the given name.
4. Naming Bean With @Bean and @Qualifier
4.1. @Bean With Value
As we saw earlier, the @Bean annotation is applied at the method level, and by default, Spring uses the method name as a bean name.
This default bean name can be overwritten β we can specify the value using the @Bean annotation:
@Configuration
public class MyConfiguration {
@Bean("beanComponent")
public MyCustomComponent myComponent() {
return new MyCustomComponent();
}
}
In this case, when we want to get a bean of type MyCustomComponent, we can refer to this bean by using the name βbeanComponentβ.
The Spring @Bean annotation is usually declared in configuration class methods. It may reference other @Bean methods in the same class by calling them directly.
4.2. @Qualifier With Value
We can also use the @Qualifier annotation to name the bean.
First, letβs create an interface Animal that will be implemented by multiple classes:
public interface Animal {
String name();
}
Now, letβs define an implementation class Cat and add the @Qualifier annotation to it with value βcatβ:
@Component
@Qualifier("cat")
public class Cat implements Animal {
@Override
public String name() {
return "Cat";
}
}
Letβs add another implementation of Animal and annotate it with @Qualifier and the value βdogβ:
@Component
@Qualifier("dog")
public class Dog implements Animal {
@Override
public String name() {
return "Dog";
}
}
Now, letβs write a class PetShow where we can inject the two different instances of Animal:
@Service
public class PetShow {
private final Animal dog;
private final Animal cat;
public PetShow (@Qualifier("dog")Animal dog, @Qualifier("cat")Animal cat) {
this.dog = dog;
this.cat = cat;
}
public Animal getDog() {
return dog;
}
public Animal getCat() {
return cat;
}
}
In the class PetShow, weβve injected both the implementations of type Animal by using the @Qualifier annotation on the constructor parameters, with the qualified bean names in value attributes of each annotation. Whenever we use this qualified name, Spring will inject the bean with that qualified name into the targeted bean.
5. Verifying Bean Names
So far, weβve seen different examples to demonstrate giving names to Spring beans. Now the question is, how we can verify or test this?
Letβs look at a unit test to verify the behavior:
@ExtendWith(SpringExtension.class)
public class SpringBeanNamingUnitTest {
private AnnotationConfigApplicationContext context;
@BeforeEach
void setUp() {
context = new AnnotationConfigApplicationContext();
context.scan("com.baeldung.springbean.naming");
context.refresh();
}
@Test
void givenMultipleImplementationsOfAnimal_whenFieldIsInjectedWithQualifiedName_thenTheSpecificBeanShouldGetInjected() {
PetShow petShow = (PetShow) context.getBean("petShow");
assertThat(petShow.getCat().getClass()).isEqualTo(Cat.class);
assertThat(petShow.getDog().getClass()).isEqualTo(Dog.class);
}
In this JUnit test, weβre initializing the AnnotationConfigApplicationContext in the setUp method, which is used to get the bean.
Then we simply verify the class of our Spring beans using standard assertions.
6. Conclusion
In this quick article, weβve examined the default and custom Spring bean naming strategies.
Weβve also learned about how custom Spring bean naming is useful in use cases where we need to manage multiple beans of the same type.
