🎉 Special Offer !    Code: GET300OFF    Flat ₹300 OFF on every Java Course
Grab Deal 🚀

Spring @Bean Annotation


Introduction

  • The @Bean annotation is used to declare a method as a Spring bean in a Java-based Spring configuration class.
  • @Bean annotation informs Spring that the method will produce a bean object which will be managed in the Spring container.

  • @Bean annotation is used at method level (inside classes annotated with @Configuration) in Spring.
  • Syntax :
    1. Create Student Bean Object
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class BeanConfig
    {
        // Below @Bean annotation is used to create Student class Bean
        @Bean
        public Student stdId() // Here method name is the bean-id / bean-name
        {
            // It will return the Student object
            return new Student();
        }
    }
    2. Different ways to access Student Bean Object
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    import in.sp.beans.Student;
    import in.sp.config.AppConfig;
    
    public class MainApp 
    {
    	public static void main(String[] args)
    	{
    		ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
    		
    		// way 1 to get Student bean object
    		// Student std = context.getBean(Student.class);
    
    		// way 2 to get Student bean object
    		Student std = (Student) context.getBean("stdId");
    
    		std.display();
    	}
    }
  • NOTE : The return type of an @Bean method is treated as the type of the bean, and the method name serves as the bean name (unless explicitly specified)

Common Usages of @Bean Annotation

The @Bean annotation can be configured with additional parameters to customize the bean's behavior.
Below are several variations and examples :-

1. Specifying Bean Name
  • By default, the method name (myService) is used as the bean name. However, we can specify a custom bean name using the name attribute:
  • Syntax :
    1. Create Student Bean Object
    @Bean(name = "myService1")
    public MyService myService()
    {
        return new MyService();
    }
    2. Different ways to access Student Bean Object
    ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
    		
    // way 1 to get MyService bean object
    MyService ms = context.getBean(MyService.class);
    
    // way 2 to get MyService bean object
    MyService ms = (MyService) context.getBean("myService1");
2. Multiple Bean Names (Aliases)
  • We can specify multiple names (aliases) for a bean by using an array in the name attribute:
  • Syntax :
    1. Create Student Bean Object
    @Bean(name = {"myService1", "myService2", "myService3"})
    public MyService myService()
    {
        return new MyService();
    }
    2. Different ways to access Student Bean Object
    ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
    		
    // way 1 to get MyService bean object
    MyService ms = context.getBean(MyService.class);
    
    // way 2 to get MyService bean object
    MyService ms = (MyService) context.getBean("myService1");
    
    // way 3 to get MyService bean object
    MyService ms = (MyService) context.getBean("myService2");
    
    // way 4 to get MyService bean object
    MyService ms = (MyService) context.getBean("myService3");
3. Defining Bean Scope
  • By default, beans are singleton-scoped. But we can specify a different scope, such as prototype, by using the @Scope annotation:
  • Syntax :
    import org.springframework.context.annotation.Scope;
    import org.springframework.beans.factory.config.ConfigurableBeanFactory;
    
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) // Creates a new instance each time
    public MyService myService()
    {
        return new MyService();
    }
4. Custom Initialization and Destruction Methods
  • We can define custom methods that will be invoked after the bean has been initialized and before it’s destroyed. We use initMethod and destroyMethod for this purpose:
  • Syntax :
    @Bean(initMethod = "init", destroyMethod = "cleanup")
    public MyService myService()
    {
        return new MyService();
    }
5. Conditional Bean Creation
  • We can use @Conditional with @Bean to conditionally create a bean based on certain conditions, such as the presence of another bean or environment properties:
  • Syntax :
    import org.springframework.context.annotation.Conditional;
    
    @Bean
    @Conditional(MyCondition.class) // Only creates bean if MyCondition is met
    public MyService myService()
    {
        return new MyService();
    }
6. Using @Bean with Parameters (Dependency Injection)
  • @Bean methods can accept parameters to inject dependencies directly from the Spring container, allowing us to specify other beans as method parameters:
  • Syntax :
    @Bean
    public MyService myService(DependencyBean dependencyBean)
    {
        return new MyService(dependencyBean);
    }