@Component vs @Service vs @Repository - Spring
Hello everyone, I hope you all are doing well.Well, today we will discuss the difference between @Component , @Service , and @Repository.
n most typical applications, we have distinct layers like data access, presentation, service, business, etc. And, in each layer, we have sundry beans. Simply put, to detect them automatically, Spring uses classpath scanning annotations. Then, it registers each bean in the ApplicationContext. Here's an expeditious overview of a few of these annotations:
- @Component is a generic stereotype for any Spring-managed component
- @Service annotates classes at the accommodation layer
- @Repository annotates classes at the assiduousness layer, which will act as a database repository
@Component
We can utilize @Component annotation to mark a bean as a Spring-managed component. In other words, it’s a generic stereotype for any Spring-managed component.We can enable an auto-scan utilizing <context:component-scan> tag. During auto-scan, Spring will scan and register all beans marked with a @Component annotation:
@Repository
@Service
- @Component is the most generic stereotype and marks a bean as a Spring-managed component
- @Repository is a stereotype used for persistence layer. It translates any persistence related exceptions into a Spring’s DataAccessException
- @Service is used for the beans at the service layer. Currently, it doesn’t offer any additional functionality over @Component