Spring Component Annotation and further stereotype annotations

spring-spring-mvc-spring-boot

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…

Quote1:

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

Quote2:

Spring provides 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. It is also possible that @Repository@Service, and @Controller may carry additional semantics in future releases of the Spring Framework. 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.

https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-stereotype-annotations

 

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.
Good Luck,
Serdar