Spring @Bean and @Configuration Simple Example

In this post under Spring Core, I will explain with example the purpose of “@Bean” and “@Configuration” annotation.

Earlier before the introduction of annotations in Spring project, we used to define beans in xml file.

For example if we had a classes as shown below

package package1;

public class Bean1 {
    public String toString() {
        return "Hello its Bean1";

package package1;

public class Bean2 {
    public String toString() {
        return "Hello its Bean2";

The bean definitions will be as shown below

    <bean id="bean1" class="package1.Bean1"/>

    <bean id="bean2" class="package1.Bean2"/>

In the above code snippet we are defining two beans with id “bean1” and “bean2” and the beans are an instance of “Bean1” and “Bean2” class.

With the introduction of annotations in latest version of Spring, we can do the same bean definition using annotations directly on java file instead of using a separate xml file.

For this we need two annotations “@Configuration” and “@Bean”.

“@Configuration” is applied at the class level, whereas “@Bean” is applied at the method level as shown below

Main Class

1  package package1;
3  import org.springframework.context.ApplicationContext;
4  import org.springframework.context.annotation.AnnotationConfigApplicationContext;
5  import org.springframework.context.annotation.Bean;
6  import org.springframework.context.annotation.Configuration;
8  @Configuration
9  public class Example1 {
10     @Bean
11     public Bean1 bean1() {
12         return new Bean1();
13     }
15     @Bean
16     public Bean2 bean2() {
17         return new Bean2();
18     }
20     public static void main(String[] args) {
21         ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example1.class);
22         Bean1 bean1 = applicationContext.getBean("bean1", Bean1.class);
23         System.out.println("Bean1: " + bean1);
24         Bean2 bean2 = applicationContext.getBean("bean2", Bean2.class);
25         System.out.println("Bean2: " + bean2);
26     }
27 }

In the above code, at line 8 adding “@Configuration” annotation to the class “Example1” informs the Spring framework that this class has methods annotated with “@Bean” annotation.

At line 10 to 13 and 15 to 18, we have annotated two methods “bean1” and “bean2” with “@Bean” annotation.

The method name becomes bean id. So in case of “bean1” method, “bean1” becomes the id of the instance of class “Bean1”. In case of “bean2” method, “bean2” becomes the id of the instance of class “Bean2”.

In the main method, at line 21, we use “AnnotationConfigApplicationContext” whose purpose is to create application context from java files having annotations. In our case it will be “Example1” class.

In the main static method, at line 22 and 24, we are getting the instances of class “Bean1” and “Bean2” using “bean1” and “bean2” as id.

In this way “@Bean” and “@Configuration” annotations are used.

Leave a Reply