Card 03/ 07
@Component, @Service, @Repository and @Controller Compared
All four register a bean the same way; they differ in what they tell a reader, and one changes behaviour.
A stereotype annotation marks a class for component scanning and says what role the class plays. Spring has four: @Component, @Service, @Repository and @Controller. All four register a bean in exactly the same way; the table compares what each one signals and the one case where the choice changes behaviour.
| Annotation | Signals | Mechanical difference from @Component |
|---|---|---|
@Component | A generic, container-managed class | None: it is the base annotation the other three build on |
@Service | Business logic, the application's use cases | None |
@Repository | Data access | Translates database-specific exceptions into Spring's DataAccessException hierarchy |
@Controller | A web request handler | Recognised by Spring MVC, which maps web requests to its methods |
Exception translation means that a failure from the database library, whatever its own exception type, reaches your code as a Spring DataAccessException, so the code above the repository does not depend on which library sits below it. It takes effect when Spring's exception-translation bean, PersistenceExceptionTranslationPostProcessor, is registered, which Spring Boot does for you.
The decision rule is about honesty for three of the four. @Component works everywhere, but @Service on a use case and @Repository on a data-access class tell the next reader what the class is for. @Repository is the one choice that also changes what happens at run time. Whichever you pick, the bean is found by the same scan and injected in the same way.
← → move through sections and cards