@Component, @Service, and @Repository

Harry · 11 Sep 2026 · 12 views

@Component, @Service, and @Repository

Spring turns annotated classes into beans through component scanning. The framework provides a family of stereotype annotations, and while they are functionally similar, they communicate intent and enable specialized behavior. Knowing when to use each keeps your codebase readable and your architecture honest.

Component is the generic marker

@Component is the generic stereotype. Annotate a class with @Component and component scanning registers it as a bean. It is the right choice for general-purpose classes that do not fit a more specific role: helpers, mappers, and wiring glue.

The specialized stereotypes

@Service marks business logic and makes the role obvious from a glance. @Repository marks data access objects and adds a translation layer: persistence exceptions are converted into Spring's DataAccessException hierarchy automatically. @Controller and @RestController mark web-handling beans in web modules.

Component scanning

Scanning starts from the package of the class annotated with @SpringBootApplication and follows every sub-package. A class outside the scanned tree is silently ignored, which is why new classes must sit under the main application package.

@Service
public class CheckoutService {
    private final PaymentGateway gateway;
    public CheckoutService(PaymentGateway gateway) {
        this.gateway = gateway;
    }
}

Behavioral differences

Only @Repository brings additional behavior (exception translation) among the main stereotypes. The others are primarily markers. Still, stereotypes matter because they standardize vocabulary across teams: you can trust a @Service to hold business logic and a @Repository to touch the database.

Key Points

  • @Component is the generic bean marker.
  • @Service signals business logic.
  • @Repository signals data access and enables exception translation.
  • Component scanning starts from the application root package.
  • Stereotypes improve architecture clarity across teams.
Share this post:

Comments (0)

Please login or register to comment.