@Component vs @Service vs @Repository: Key Differences and Usage
@Component is a generic stereotype for any Spring-managed component, while @Service is a specialized @Component used for service layer logic, and @Repository is another specialized @Component meant for data access layers with added exception translation support.Quick Comparison
Here is a quick table to compare the main aspects of @Component, @Service, and @Repository annotations in Spring.
| Aspect | @Component | @Service | @Repository |
|---|---|---|---|
| Purpose | Generic Spring bean | Service layer logic | Data access layer |
| Exception Translation | No | No | Yes, translates persistence exceptions |
| Semantic Meaning | General use | Indicates business logic | Indicates DAO or repository |
| Usage Layer | Any layer | Service/business layer | Persistence/DAO layer |
| Spring Stereotype | Base stereotype | Specialized stereotype | Specialized stereotype |
Key Differences
@Component is the most general annotation to mark a class as a Spring-managed bean. It does not carry any specific semantic meaning beyond that, so it can be used anywhere in the application.
@Service is a specialization of @Component that indicates the class holds business logic or service layer code. It helps developers and tools understand the role of the class but does not add extra behavior by itself.
@Repository also extends @Component but is intended for the data access layer. It adds automatic exception translation, converting database exceptions into Spring’s unified unchecked exceptions, which helps in consistent error handling.
Code Comparison
Example of a generic Spring bean using @Component:
import org.springframework.stereotype.Component; @Component public class NotificationHelper { public void sendNotification(String message) { System.out.println("Sending notification: " + message); } }
@Service Equivalent
Example of a service layer class using @Service:
import org.springframework.stereotype.Service; @Service public class NotificationService { public void notifyUser(String message) { System.out.println("Notifying user: " + message); } }
When to Use Which
Choose @Component when you need a generic Spring bean without specific role semantics. Use @Service to mark classes that contain business logic or service operations, making your code clearer and easier to maintain. Use @Repository for classes that interact with the database or data sources, benefiting from Spring’s exception translation and clearer intent.
Key Takeaways
@Component is a generic stereotype for any Spring-managed bean.@Service marks service layer classes with business logic but adds no extra behavior.@Repository marks data access classes and enables exception translation.