java – Controllers and Services Notes


In Spring there are 3 class notes @Component , @Service , @Controller and @Repository .

I know @Component is the only one that can be used in all cases ( Controller , Service and Repository ).

But what are the advantages and disadvantages of using this annotation which is more generic?


Unlike the generic @Component annotation, specific annotations mark classes with stereotypes, just like in the UML.

This way, if a class is annotated with @Service you can assume that it contains business rules, if the annotation is @Repository is obvious that the class implements the Respository pattern (it is not the same as DAO, but it is similar) and if the annotation is @Controller you can also bind directly to a controller from the MVC model.

Although at first it looks like just an ornament, it is possible to list some advantages:

  • Aids in application layer separation.
  • It facilitates the use of POA (AOP – Aspect Oriented Programming), as in the case of the Spring Data JPA module, which dynamically "generates" the implementation of annotated interfaces with Repository.
  • Allows the specific handling of exceptions thrown by specific layers, where we have again the example of the data access layer ( Repository ), where Spring will translate specific exceptions from a database into standardized classes.
  • You can create any functionality that needs general treatment by layer, just use a little imagination. 🙂

Honestly, I didn't find any disadvantages in using specific annotations compared to generic annotation. The only caveat is regarding the performance of component-scan , which finds the annotations automatically (regardless of which one you are using), as it can delay the application's startup. Mapping beans to XML improves startup time if this is critical.

Scroll to Top