Controller and service annotations

Asked

Viewed 971 times

7

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

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

But what is the advantage and disadvantage of using this annotation that is more generic?

1 answer

6


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

Thus, if a class is annotated with @Service you can assume that it contains business rules if the annotation is @Repository it is obvious that the class implements Pattern Respository (is not equal to DAO, but it is similar) and if the annotation is @Controller you can also associate directly to a controller of the MVC model.

Although at first it seems just a garnish, it is possible to list some advantages:

  • Help in separating layers of the application.
  • 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 specific processing of exceptions launched by specific layers, where we have again the example of the data access layer (Repository), where Spring will translate database-specific exceptions into standard classes.
  • You can create any functionality that needs general treatment per layer, just use a little imagination. :)

Honestly, I did not find disadvantages in the use of specific annotations in relation to generic annotations. The only caveat is the performance of component-scan, that finds annotations automatically (regardless of which one you are using), as it may delay the application startup. Mapping XML Beans improves boot time if this is something critical.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.