What is the difference between @Component, @Service, and @Repository?
In Spring, @Component, @Service, and @Repository are stereotypes used to mark classes as Spring-managed beans. Here’s the difference:
- @Component:
- Generic stereotype for any Spring-managed bean.
- Used when the class doesn’t fit a specific role.
- @Service:
- Specialized @Component.
- Indicates that the class contains business logic or service-layer code.
- @Repository:
- Specialized @Component.
- Used for Data Access Objects (DAO).
- Adds exception translation for database errors into Spring’s DataAccessException.
Key Point
They function similarly, but @Service and @Repository provide semantic meaning, improving code readability and clarity.