Giving custom name to @Bean annotated beans

In this post under Spring Core, I will show with example how to give custom id to beans.

Whenever we define a bean with @Bean annotated method, we do it as below


    public Bean1 bean1() {
        return new Bean1();
    }

The bean id by default will be same as method name. So in the above case, the bean id will be “bean1”.

We can change this. We can provide a custom name as shown below


    @Bean("exampleBean1")
    public Bean1 bean1() {
        return new Bean1("exampleBean1");
    }

In the above code snippet I have given a custom name “exampleBean1” as bean id by setting the “value” attribute of “@Bean” annotation.

We can write it in another way also as shown below


    @Bean(value = "exampleBean2")
    public Bean1 bean2() {
        return new Bean1("exampleBean2");
    }

In the above code snippet I have explicitly mentioned the “value” attribute.

Below is the complete code for your reference.

Bean Class Structure


package package4;

public class Bean1 {
    private String title;

    public Bean1(String title) {
        this.title = title;
    }

    public Bean1() {
        this.title = "Bean1";
    }

    @Override
    public String toString() {
        return "Hello its " + title;
    }
}

In this way we can give custom names to beans.

Below is the complete main code for your reference

Main Class


package package4;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Example4 {
    @Bean("exampleBean1")
    public Bean1 bean1() {
        return new Bean1("exampleBean1");
    }

    @Bean(value = "exampleBean2")
    public Bean1 bean2() {
        return new Bean1("exampleBean2");
    }

    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example4.class);
        Bean1 bean = applicationContext.getBean("exampleBean1", Bean1.class);
        System.out.println(bean);

        bean = applicationContext.getBean("exampleBean2", Bean1.class);
        System.out.println(bean);

        bean = applicationContext.getBean("bean1", Bean1.class);
        System.out.println(bean);
    }
}

Leave a Reply