Sunday 1 October 2023

Difference between @Component and @Bean annotation in Spring

          As we discussed about Stereotype annotations in one of the blog post, the @Component annotation is a  stereotype annotation in Spring. If you want to convert any java class as a Spring managed bean then to use component annotation. It will scan during the project start up and will create the bean if the component class exist in the component scan package.

        @Bean annotation is used to create a bean, this can use along with Configuration annotation. Bean annotation is a method level annotation and name of the method serves as a bean name. Component annotation is a class level annotation.

Difference between @Bean and @Component

Example:-

@Component
public class ProductUtil{

   //methods


}

@Bean annotation

@Configuration
class HMSAppConfiguration{

   @Bean
   public Customer getCustomer(){
      return new Customer();
   }
}

Youtube Video:- 

Thank you for reading the blog.

No comments:

Post a Comment