Close

Spring - Using @Bean annotation

[Last Updated: Nov 27, 2020]

@Bean is a method-level annotation and a direct analog of the XML <bean/> element.

We use it to declare bean. During startup time the bean definition is registered to the ApplicationContext.

We can use the @Bean annotation in a @Configuration class.

Example


Bean class

package com.logicbig.example;

public class Calculator {

  public int sum(int x, int y) {
      return x + y;
  }
}

Using @Bean in the @Configuration class

package com.logicbig.example;

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

@Configuration
public class AppConfig {

  @Bean
  Calculator calculator() {
      return new Calculator();
  }

  public static void main(String[] args) {
      AnnotationConfigApplicationContext context =
              new AnnotationConfigApplicationContext(AppConfig.class);
      Calculator calculator = context.getBean(Calculator.class);
      int sum = calculator.sum(5, 7);
      System.out.println(sum);
  }
}

Output

12

Example Project

Dependencies and Technologies Used:

  • spring-context 4.3.2.RELEASE: Spring Context.
  • JDK 1.8
  • Maven 3.6.3

Spring - @Bean annotation example Select All Download
  • spring-bean-annotation-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • AppConfig.java

    See Also