What's the difference between @Component, @Repository & @Service annotations in Spring?

In Spring 2.0 and later, the @Repository annotation is a marker for any class that fulfills the role or stereotype (also known as Data Access Object or DAO) of a repository. Among the uses of this marker is the automatic translation of exceptions.
Spring 2.5 introduces further stereotype annotations: @Component, @Service, and @Controller. @Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.
Therefore, you can annotate your component classes with @Component, but by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts.
Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated above, @Repository is already supported as a marker for automatic exception translation in your persistence layer.
| Annotation | Meaning                                             |
| @Component | generic stereotype for any Spring-managed component |
| @Repository| stereotype for persistence layer                    |
| @Service   | stereotype for service layer                        |
| @Controller| stereotype for presentation layer (spring-mvc)      |

1 comment:

  1. I think that it is also worth mentioning that these stereotypes are intended to mark layers with in a multi-tier web application. Components within the presentation, business, and persistence layers are annotated respectively by Component, Service and Repository as follows:

    @Repository -> data access components
    @Service -> service components
    @Controller -> controller components
    @Component -> any other component

    I wrote a blog article examining in more details these difference. I hope you don't mind me mentioning it here: https://readlearncode.com/2016/02/13/insights-from-stackoverflow-most-voted-for-spring-4-questions/#1