What is the difference between @Component and @Bean?
Quick Answer
@Component is a class-level annotation, detected via component scanning, that tells Spring to manage that entire class as a bean — appropriate for classes you own and can annotate directly. @Bean is a method-level annotation inside an @Configuration class, used to explicitly declare and construct a bean yourself in code — necessary for third-party classes you can't annotate, or when bean creation needs custom logic/parameters.
Detailed Answer
Both register a Spring-managed bean, but via different mechanisms suited to different situations:
@Component (and its stereotype specializations) is placed directly on a class, and picked up automatically by component scanning:
@Component
class EmailNotifier implements Notifier {
// Spring instantiates this via component scanning, no explicit wiring code needed
}
This only works for classes you own and can annotate — you can't add @Component to a class from a third-party JAR.
@Bean is placed on a method inside an @Configuration class; the method's return value becomes the managed bean, and you write the actual construction logic yourself:
@Configuration
class AppConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.setConnectTimeout(Duration.ofSeconds(5)).build(); // full control over construction
}
}
When @Bean is necessary (not just a style choice):
- Wiring up a third-party class you can't put
@Componenton (RestTemplate, an external SDK client). - When bean creation requires custom logic or conditional configuration beyond what a constructor/field injection can express.
- When you need multiple beans of the same type with different configurations (e.g., two differently-configured
RestTemplatebeans, disambiguated by method name or an explicit bean name).
Rule of thumb: use @Component (or a stereotype) for your own application classes; use @Bean inside @Configuration classes for anything you don't own, or that needs custom construction logic.