Giving custom name to @Component annotated beans

In this post under Spring Core, I will show with example how to give custom names to classes annotated with “@Component” annotation.

By default when we annotate a class with “@Component” annotation, the name of the bean will be created from the class name, where the first letter of the class name will be lowercase.

So if a class named “Bean1” is annotated with “@Component”, its bean name will be “bean1”. The character “B” is in lowercase in the bean name.

We can give a custom name instead of depending on the Spring framework to come up with a name as shown below.

1  package package8;
2  
3  import org.springframework.stereotype.Component;
4  
5  @Component("exampleBean1")
6  public class Bean1 {
7      @Override
8      public String toString() {
9          return "Hello its Bean1";
10     }
11 }

In the above code at line 5, we have created a bean with custom name “exampleBean1”.

In this way we can define a custom name to classes annotated with “@Component” annotation.

Below is the complete main code for your reference.

Main class

1  package package8;
2  
3  import org.springframework.context.ApplicationContext;
4  import org.springframework.context.annotation.AnnotationConfigApplicationContext;
5  import org.springframework.context.annotation.ComponentScan;
6  
7  @ComponentScan(basePackages = "package8")
8  public class Example8 {
9      public static void main(String[] args) {
10         ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example8.class);
11         Bean1 bean1 = applicationContext.getBean("exampleBean1", Bean1.class);
12         System.out.println(bean1);
13     }
14 }

In the above code, at line 11, we get the bean using the custom name.

Leave a Reply