What is the difference between @Component, @Service, @Repository, and @Controller?
Quick Answer
All four are stereotype annotations that mark a class as a Spring-managed bean discovered via component scanning; functionally, @Service, @Repository, and @Controller are meta-annotated with @Component, so they're all detected identically by the container. They differ in the semantic role they signal and, in @Repository's case, an actual behavioral difference: it enables automatic translation of persistence-technology-specific exceptions into Spring's unified DataAccessException hierarchy.
Detailed Answer
All four are stereotype annotations, and @Service, @Repository, and @Controller are each themselves annotated with @Component — meaning component scanning treats all four identically for the basic purpose of "register this class as a Spring bean":
@Component // generic — "this is a Spring-managed bean"
class DataFormatter { }
@Service // business/service-layer logic
class OrderService { }
@Repository // data-access layer
class OrderRepository { }
@Controller // web layer, returns view names (or @RestController for JSON/text bodies directly)
class OrderController { }
Why bother with more specific ones, if they're functionally interchangeable for bean registration?
- Readability/intent — seeing
@Repositoryon a class immediately communicates its architectural role, which plain@Componentdoesn't. @Repositoryhas a genuine behavioral difference: Spring registers aPersistenceExceptionTranslationPostProcessorfor beans annotated@Repository, which automatically translates low-level, technology-specific persistence exceptions (e.g., a JPAPersistenceException, a JDBCSQLException) into Spring's unified, uncheckedDataAccessExceptionhierarchy — letting service-layer code catch a consistent, technology-agnostic exception type regardless of which persistence technology the repository actually uses underneath.@Controller/@RestControlleradditionally participate in Spring MVC's request-handling machinery — being detected specifically as web-layer components that can hold@RequestMapping-annotated handler methods.
Rule of thumb: always prefer the most specific stereotype available for the layer a class belongs to — it costs nothing, documents architecture more clearly, and (for @Repository) unlocks a genuinely useful behavior.