In this post I would like to share with you some enlightening quotes from spring documentation. Here you will see the difference between some of the spring annotations like @component, @service, @repository, @controller, what it means to use them or can you use them for one another…
@Component indicates that an annotated class is a “component”. Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.
Other class-level annotations may be considered as identifying a component as well, typically a special kind of component: e.g. the @Repository annotation or AspectJ’s @Aspect annotation.
Spring provides further stereotype annotations:
@Componentis a generic stereotype for any Spring-managed component.
@Controllerare specializations of
@Componentfor 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
@Controllerinstead, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts. It is also possible that
@Controllermay carry additional semantics in future releases of the Spring Framework. Thus, if you are choosing between using
@Servicefor your service layer,
@Serviceis clearly the better choice. Similarly, as stated above,
@Repositoryis already supported as a marker for automatic exception translation in your persistence layer.
Result: Although currently it is technically possible to use one for the other, you should not do this. Use @Controller for your mvc controllers, use @Repository for your Data Access Objects (DAOs) etc. Don’t forget, as the documentation states, it is possible that in the future releases these annotations could mean and do more then they do now.
Hope this helps.