What is the difference between @Component and @Bean?
Options
- There is no difference; both register a bean the same way
@Componentscans your class;@Beanuses a method result (Correct option)@Beanis meant for tests only, not for production code@Componentcan only be placed on interfaces, not classes
Answer
@Component goes on a class you own and is found by scanning; @Bean goes on a method inside a @Configuration class and registers the returned object, useful for third-party classes
Why
@Component (and its stereotypes) annotates your own class, and Spring discovers it by component scanning.
@Bean is placed on a method in a @Configuration class. The returned object is registered as a bean. Use it when you cannot annotate the class (a library class like ObjectMapper or RestClient) or when construction needs custom logic.
@Configuration
public class AppConfig {
@Bean
public Clock clock() {
return Clock.systemUTC();
}
}Remember
@Component = my class. @Bean = a factory method for any class.