@Component, @Service, @Repository

Spring Boot · lesson 6 of 39 · 2 min read

Pick the right stereotype annotation and know which one adds real behaviour.

Open this lesson in the learning hub

Key points

  • All three are @Component underneath. Component scan finds them and registers a bean.
  • @Service is a pure label for business logic. It adds no behaviour — it adds readability.
  • @Repository does add behaviour: it translates vendor exceptions into Spring's DataAccessException.
  • @Controller and @RestController mark web entry points and enable request mapping.
  • Rule of thumb: web layer is thin, @Service holds the rules, @Repository only talks to the database.

Example

@RestController          // HTTP in, JSON out
class OrderController { }

@Service                 // business rules, transactions
class OrderService { }

@Repository              // data access + exception translation
class JdbcOrderRepository { }

@Component               // anything else: a mapper, a validator, a scheduler
class OrderMapper { }

Same wiring, different intent — except @Repository, which really does translate exceptions.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Spring Boot course, and every lesson in it is listed on the Spring Boot contents page.