Sobes.tech
Junior — Middle

What is the difference between the @Bean annotation and the @Component annotation in the context of Spring?

sobes.tech AI

Answer from AI

The @Component annotation is used for automatic detection and registration of a class as a Spring bean through the component scanning mechanism. It is applied to classes that should be managed by the Spring container.

The @Bean annotation is applied to methods within a class, such as one annotated with @Configuration, and indicates that the object returned by this method should be registered as a bean in the Spring context.

Main differences:

  • @Component — placed on a class to have Spring automatically create a bean of this class.
  • @Bean — placed on a method that manually creates and returns a bean.

Example:

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

@Component
public class MyComponent {
    // This class will automatically become a bean
}
What is the difference between the @Bean annotation… - sobes.tech