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

Question:

The above annotations are closely related, so my questions are as follows:

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

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

2- will it 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 it should have @Repository ?

Answer:

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

Also, classes marked @Repository are eligible to use a PersistenceExceptionTranslationPostProcessor postprocessor, which translates DB errors to DataAccessException type DataAccessException (as indicated by the class javadoc)

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

Scroll to Top