What is the difference between @Component, @Service, @Repository, and @Controller?

7 minbeginnerstereotype-annotationscomponentservicerepository

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?

  1. Readability/intent — seeing @Repository on a class immediately communicates its architectural role, which plain @Component doesn't.
  2. @Repository has a genuine behavioral difference: Spring registers a PersistenceExceptionTranslationPostProcessor for beans annotated @Repository, which automatically translates low-level, technology-specific persistence exceptions (e.g., a JPA PersistenceException, a JDBC SQLException) into Spring's unified, unchecked DataAccessException hierarchy — letting service-layer code catch a consistent, technology-agnostic exception type regardless of which persistence technology the repository actually uses underneath.
  3. @Controller/@RestController additionally 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.