Spring Boot @Bean Annotation Example

 In this tutorial, we will learn everything about Spring Boot @Bean annotation with examples.

@Bean Annotation Overview

The @Bean annotation indicates that a method produces a bean to be managed by the Spring container. 

The @Bean annotation is usually declared in the Configuration class to create Spring Bean definitions.

YouTube Video - @Bean Annotation

@Bean Annotation Example

In order to demonstrate the usage of @Bean annotation, let's create a couple of Java classes.

Student and Address

class Student{
    private Address address;

    public Student(Address address){
        this.address = address;
    }

    public void print(){
        System.out.println("Student class method called ...");
        address.print();
    }
}

class Address{

    public void print(){
        System.out.println("Address class method called ...");
    }
}

AppConfig Class

Next, let's create a Java configuration class annotated with @Configuration annotation. Within this class, let's create bean definitions using @Bean annotation.
@Configuration
class AppConfig{

    @Bean
    public Address address(){
        return new Address();
    }

    @Bean
    public Student student(){
        return new Student(address());
    }
}

Bean Names

By default, the bean name is the same as the method name. We can specify the bean names using @Bean(name = “beanName”).

For example:

    @Bean(name = "addressBean")
    public Address address(){
        return new Address();
    }

    @Bean(name = "studentBean")
    public Student student(){
        return new Student(address());
    }

Define Mulitple Bean Names

We can also specify multiple names for a single Spring bean. 

For example:
    @Bean(name = {"studentBean", "studentDemo", "studentComponent"})
    public Student student(){
        return new Student(address());
    }
Next, we can retrieve the student Spring bean object using any of these bean names. For example:
Student student = (Student) applicationContext.getBean("studentBean");
Or 
Student student = (Student) applicationContext.getBean("studentDemo");
Or 
Student student = (Student) applicationContext.getBean("studentComponent");

@Bean initMethod and destroyMethod attributes

@Bean annotation provides initMethod and destroyMethod attributes to perform certain actions after bean initialization or before bean destruction by a container.

For example, the Student Spring bean has initMethod and destroyMethod attributes:

@Configuration
class AppConfig{

    @Bean(name = "addressBean")
    public Address address(){
        return new Address();
    }

    @Bean(name = "studentBean", initMethod = "init", destroyMethod = "destroy")
    public Student student(){
        return new Student(address());
    }
}
Next, create init() and destroy() methods in Student class:
class Student{
    private Address address;

    public Student(Address address){
        this.address = address;
    }

    public void print(){
        System.out.println("Student class method called ...");
        address.print();
    }

    public void init(){
        System.out.println("Intialization logic");
    }

    public void destroy(){
        System.out.println("Destruction logic");
    }
}

Testing

Run the below code to test all the @Bean annotation use cases:

public class BeanAnnotationDemo {

    public static void main(String[] args) {
        try(var applicationContext = new AnnotationConfigApplicationContext(AppConfig.class)){
            //Student student = applicationContext.getBean(Student.class);
            Student student = (Student) applicationContext.getBean("studentBean");
            String[] beanNames = applicationContext.getBeanDefinitionNames();
            for (String bean: beanNames){
                System.out.println(bean);
            }
            student.print();
        }
    }
}

Complete Code

Here is the complete code for your reference:
package com.spring.core.beans;

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

class Student{
    private Address address;

    public Student(Address address){
        this.address = address;
    }

    public void print(){
        System.out.println("Student class method called ...");
        address.print();
    }

    public void init(){
        System.out.println("Intialization logic");
    }

    public void destroy(){
        System.out.println("Destruction logic");
    }
}

class Address{

    public void print(){
        System.out.println("Address class method called ...");
    }
}

@Configuration
class AppConfig{

    @Bean(name = "addressBean")
    public Address address(){
        return new Address();
    }

    @Bean(name = "studentBean", initMethod = "init", destroyMethod = "destroy")
    public Student student(){
        return new Student(address());
    }
}

public class BeanAnnotationDemo {

    public static void main(String[] args) {
        try(var applicationContext = new AnnotationConfigApplicationContext(AppConfig.class)){
            //Student student = applicationContext.getBean(Student.class);
            Student student = (Student) applicationContext.getBean("studentBean");
            String[] beanNames = applicationContext.getBeanDefinitionNames();
            for (String bean: beanNames){
                System.out.println(bean);
            }
            student.print();
        }
    }
}

Conclusion

 In this tutorial, we have seen how to use @Bean annotation to create and manage Spring bean by Spring container. We have also seen how to use initMethod and destroyMethod attributes of @Bean annotation.

Related Spring and Spring Boot Annotations

Comments