Notes for controllers and services

6

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

I know that @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?

    
asked by anonymous 11.12.2013 / 17:23

1 answer

5

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

So, 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 the pattern Respository (it is not the same as DAO, but it is similar) and if the annotation is @Controller you can also associate directly with an MVC model driver. p>

Although at first it looks just like an ornament, you can list some advantages:

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

I honestly did not find any disadvantages in using the specific annotations with regard to generic annotation. The only caveat is the component-scan performance, which finds the annotations automatically (regardless of which one you're using), as it may delay the startup of the application. Mapping beans to XML improves boot time if this is critical.

    
12.12.2013 / 00:21