Difference between @Bean and @Component annotation in Spring.

SpringObject Oriented ProgrammingProgramming

 Spring supports multiple types annotations such as @Component,@Controller,@service @Repository and @Bean. All theses can be found under the org.springframework.stereotype package.

When classes in our application are annotated with any of the above mentioned annotation then during project startup spring scan(using @componentScan) each class and inject the instance of the classes to the IOC container. Another thing the @ComponentScan would do is running the methods with @Bean on it and restore the return object to the Ioc Container as a bean.

Sr. No.Key@Bean@Component
Auto detection
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.
Spring Container
Bean can be created even class is outside the spring container
We can’t create bean if class is outside spring container
Class/Method  Level Annotation
It is a method level annotation
It is a class level annotation
It works only when class is also annotated with @Configuration
It works without
@Configuration annotation
Use Case
We should use @bean, if you want specific implementation based on dynamic condition.
We can’t write specific implementation based on dynamic condition

Example of @Component

public class Pizza{



Example of @Bean

class AppConfiguration{

   public User getUse(){
      return new User();
Published on 09-Sep-2020 12:24:20