Sobes.tech
Junior — Middle

What is the main function of the @Bean annotation in Spring configuration and why is it used?

sobes.tech AI

Answer from AI

The @Bean annotation in Spring is used to define a method that returns an object managed by the Spring container as a component (bean). This allows explicit creation and configuration of class instances in configuration classes.

Main functions of @Bean:

  • Create and register an object in the Spring context.
  • Allow programmatic configuration of object creation (e.g., setting constructor parameters, dependencies).
  • Ensure lifecycle management of this object by Spring.

Example:

@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }
}

Thus, @Bean is used for explicit component definition, especially when component scanning (@Component) is not suitable or more fine-tuned configuration is needed.