Am I correct, thinking that @Bean and @Component annotations are the same, but first is for classes and another is for methods?
In both cases container just creates appropriate beans, right?
There are some important implications we should note because of the differences between @Component and @Bean. @Component is a class-level annotation, but @Bean is at the method level, so @Component is only an option when a class's source code is editable. @Bean can always be used, but it's more verbose.
@Component is a class level annotation whereas @Bean is a method level annotation and name of the method serves as the bean name. @Component need not to be used with the @Configuration annotation where as @Bean annotation has to be used within the class which is annotated with @Configuration.
In the component classes, we can use any valid annotation along with @Bean method and it's parameters, exactly the same way we use them in @Configuration classes (e.g. @Lazy, @Qualifier, @Primary etc).
No. It is used to explicitly declare a single bean, rather than letting Spring do it automatically. If any class is annotated with @Component it will be automatically detect by using classpath scan. We should use @bean, if you want specific implementation based on dynamic condition.
Not quite. They belong to different concepts.
@Component
is a stereotype annotation. A class annotated with this annotation will be auto detected during class path scanning. See also Spring reference documentation chapter 5.10. Other than that the @Bean
annotation belongs to the Java configuration feature. Within a configuration class this annotation is used to mark methods that define beans.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With