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. @Service, @Repository, and @Controller are meta-annotated with @Component, so the container detects all four identically. They differ in the semantic role they signal, and @Repository has a real behavioral difference: it enables automatic translation of persistence-technology-specific exceptions into Spring's unified DataAccessException hierarchy.
Detailed Answer
All four are stereotype annotations. @Service, @Repository, and @Controller are each themselves annotated with @Component — so 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. It automatically translates low-level, technology-specific persistence exceptions (a JPAPersistenceException, a JDBCSQLException) into Spring's unified, uncheckedDataAccessExceptionhierarchy. Service-layer code can then catch one 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.