Card 03/ 07

ComparisonDifficulty: Intermediate1 min

@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.

The stereotype annotations
AnnotationSignalsMechanical difference from @Component
@ComponentA generic, container-managed classNone: it is the base annotation the other three build on
@ServiceBusiness logic, the application's use casesNone
@RepositoryData accessTranslates database-specific exceptions into Spring's DataAccessException hierarchy
@ControllerA web request handlerRecognised 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.