What is the difference between the annotations Repository, Component, Controller, and Service?
sobes.tech AI
Answer from AI
These Spring Framework annotations are used to mark classes as Spring Beans managed by the container. They are specialized forms of @Component and are intended to improve semantics and ease of use.
-
@Component: A generic annotation indicating that the class is a Spring component and should be detected during component scanning. Other specialized annotations are derived from it. -
@Repository: Used for classes interacting with data sources (DAO, repositories). It adds exception handling functionality specific to data access (e.g., translating JPA-specific exceptions into Spring'sDataAccessException). -
@Service: Used for classes containing business logic. Semantically indicates a service layer. Applied to classes coordinating interactions between presentation and data layers. -
@Controller: Used for classes handling web requests and returning responses. Used in the MVC web layer to process incoming HTTP requests.
| Annotation | Purpose | Application Layer | Additional Capabilities (compared to @Component) |
|---|---|---|---|
@Component |
General Spring Bean | Any | None |
@Repository |
Data access | Data layer | Exception translation for data access |
@Service |
Business logic | Service layer | None (semantic purpose) |
@Controller |
Web request handling | Presentation layer | HTTP request processing, URI mapping |
All these annotations essentially lead to the creation of a Spring Bean, but @Repository and @Controller provide additional capabilities specific to their intended use. @Service primarily serves as a semantic annotation.