Difference between annotations @Component, @Repository and @Service in Spring?

6

The previous entries are very related, so my questions are as follows:

1- Can the annotations @Component, @Repository and @Service be used interchangeably in Spring or do they provide any particular functionality besides acting as an annotation?

In other words, if I have a service class and change the annotation of @Service to @Component :

2- Will you continue to behave in the same way? Or does the annotation also influence the behavior and functionality of the class?

3-Could you exchange them and for example use @Service when conceptually you should have @Repository ?

    
asked by UHDante 21.06.2018 в 02:49
source

2 answers

7

@Repository and @Service are specializations of @Component , adding a semantic value that indicates the utility of the annotated class ( @Repository for access to BD and @Service for the business layer).

In addition, classes marked as @Repository are eligible to use a postprocessor PersistenceExceptionTranslationPostProcessor , which translates the errors of BD to exceptions of type DataAccessException (as indicated by the javadoc of the class)

I understand that you will have no problem changing one annotation for another unless you use that postprocessor.

    
answered by 21.06.2018 / 08:58
source
2

As the Spring documentation says well , @Component is the main stereotype and indicates that a class with this annotation is a component or Spring Bean.

@Repository , @Service and @Controller are specifications of the @Component annotation for specific cases, for example, for the persistence of data, services or for the presentation layer respectively.

Therefore, you can annotate your beans with the @Component annotation, but by annotating them with @Repository , @Service or > @Controller you will get additional benefits since some of the Spring modules process these annotations differently.

Generally you can use one instead of another, but it is not recommended that you do it.

    
answered by 27.06.2018 в 11:37