Spring Top

Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:

>> LEARN SPRING

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.

As usual, the complete code for this article is available over on GitHub.

Spring bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> THE COURSE
Generic footer banner
Comments are closed on this article!