Skip to main content
PreparationZone Logo
PrepZone

@Component, @Service, @Repository, @Controller

Stereotype annotations that tell Spring what role each class plays in your app.

Pass checkpoint below

Why this matters

  • Consistent stereotype usage makes the BookStore codebase navigable — any developer knows where to find controllers vs services.
  • @Repository enables automatic translation of persistence exceptions to Spring's DataAccessException hierarchy.
  • Mixing stereotypes incorrectly (business logic in a @Controller) breaks layering and testability.

@Component family

L1 · Fresher

@Service, @Repository, and @Controller are specializations of @Component with the same scanning rules. They document intent in BookStore's package structure.

@Repository and persistence exceptions

L2 · Intermediate

Spring translates data-access exceptions to DataAccessException for @Repository beans. Controllers should not swallow JDBC errors without mapping them to HTTP problems.

Component scan boundaries

L3 · Advanced

@SpringBootApplication scans the package of the main class and sub-packages. Moving BookStore code outside that tree requires @ComponentScan on a configuration class.

Custom stereotype meta-annotations

L4 · Expert

Define @BookStoreFacade meta-annotated with @Service for architectural rules. Keeps scanning fast and encodes layer conventions in large codebases.

ApplicationContext
BookController@RestController
BookService@Service
BookRepository@Repository
DataSourceAuto-configured

Arrows show @Autowired wiring — container injects at startup

The ApplicationContext reads configuration, creates beans, and wires dependencies automatically.

The stereotype hierarchy

All stereotypes are meta-annotated with @Component:

Java
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface Service { }

Spring treats @Service, @Repository, @Controller, and @RestController identically for bean registration. The difference is semantic and enables specialised processing.

Stereotypes in BookStore

  • @Component — Generic bean; use for utilities, adapters, and infrastructure classes.
  • @Service — Business logic layer; BookService, OrderService, PricingService.
  • @Repository — Data access layer; BookRepository implementations and Spring Data interfaces.
  • @Controller — MVC controller returning view names (Thymeleaf pages).
  • @RestController — API controller returning serialized bodies (@Controller + @ResponseBody).

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 7 sections

  • @Service in BookStore
  • @Repository and Spring Data
  • @RestController for APIs
  • @Component for everything else
  • Component scanning boundaries
  • Naming and multiple implementations
  • Stereotype vs @Bean

Test yourself

Answer these before moving on — recall is what makes it stick.