Sobes.tech
Middle

Where is the @Bean annotation used?

sobes.tech AI

Answer from AI

The @Bean annotation is used in the Spring Framework.

Main use cases:

  • Methods in @Configuration classes: This is the most common case. A method annotated with @Bean creates, configures, and returns a new object that Spring manages as a bean.

    // Example of usage in a configuration class
    @Configuration
    public class AppConfig {
    
        @Bean
        public MyService myService() {
            // Creating and configuring an instance of MyService
            return new MyServiceImpl();
        }
    }
    
  • Methods in @Component, @Service, @Repository, and other stereotype-annotated classes: Although @Configuration is preferred for bean declaration, @Bean can also be used in other stereotype classes. However, this is less common and may be less obvious.

    // Example of usage in a service class (less typical)
    @Service
    public class SomeService {
    
        @Bean
        public AnotherComponent anotherComponent() {
            return new AnotherComponent();
        }
    }
    

Purpose:

@Bean indicates to Spring that the object returned by this method should be registered in the application context as a managed bean. This allows it to be injected into other components using @Autowired.

Parameters of @Bean:

The annotation has optional parameters for bean configuration:

  • name: Allows specifying one or more custom names for the bean. By default, the bean name matches the method name.
  • initMethod: Specifies the name of the initialization method to be called after the bean is created.
  • destroyMethod: Specifies the name of the method to be called before the bean is destroyed.
// Example with parameters
@Bean(name = {"myUniqueService", "aliasService"}, initMethod = "postConstruct", destroyMethod = "preDestroy")
public MyService myServiceWithLifecycle() {
    return new MyServiceImpl();
}