@Component
is a Spring annotation that is used to indicate that a class is a component of the application and should be managed by the Spring framework. It’s a more generic annotation that can be used in any layer of the application.@Bean
is another Spring annotation that is used to indicate that a method is a factory method for creating an object that should be managed by the Spring framework. The method annotated with@Bean
will return an object that will be registered as a Spring bean and can be later injected into other components.- In summary,
@Component
is used to mark a class as a Spring bean, while@Bean
is used to mark a method as a factory method for creating a Spring bean. - The main difference between these two annotations is that
@Component
is used to mark a class as a Spring bean, while@Bean
is used to mark a method that returns an object that will be registered as a Spring bean. @Component
is used for classes that are automatically detected by Spring during a classpath scan and registered as Spring beans, while@Bean
is used for explicit registration of a single bean within a@Configuration
class.@Component
can be used in any layer of the application, but@Bean
is mainly used in the configuration layer.
Summery of Differences @Component and @Bean
@Component | @Bean |
auto detects and configures the beans using classpath scanning | explicitly declares a single bean, rather than letting Spring do it automatically |
does not decouple the declaration of the bean from the class definition | decouples the declaration of the bean from the class definition |
need not to be used with the @Configuration annotation | @Bean annotation has to be used within the class which is annotated with @Configuration |
a class level annotation | a method level annotation and name of the method serves as the bean name |
@Component has different specializations like @Controller, @Repository and @Service | @Bean has no specializations |
We cannot create a bean of a class using @Component, if the class is outside spring container | we can create a bean of a class using @Bean even if the class is present outside the spring container |