Sobes.tech
Junior — Middle

How to distinguish an @Component annotation from a @Bean 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 classpath scanning (component scanning). It is placed above the class and tells Spring that this class should be instantiated and managed by the container.

@Bean is an annotation applied to a method within a class annotated with @Configuration. The method with @Bean returns an object that will be registered in the Spring context as a bean. This is a more explicit way of creating a bean when you need control over the creation process or want to use third-party classes.

Example:

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

@Component
public class MyComponent {
    // This class will be automatically registered as a bean
}

In summary:

  • @Component annotates a class, and the bean is created automatically during scanning.
  • @Bean annotates a method, and the bean is created explicitly through the method's return object.
How to distinguish an @Component annotation from a… - sobes.tech