Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (2.6k points)

Can @Component, @Repository and @Service annotations be used interchangeably in Spring or do they provide any particular functionality besides acting as a notation device?

In other words, if I have a Service class and I change the annotation from @Service to @Component, will it still behave the same way?

Or does the annotation also influence the behavior and functionality of the class?

1 Answer

0 votes
by (46k points)

Let's first understand the meaning of @Component, @Repository, and @Service:

1. @Component is a universal stereotype for any Spring-managed component or bean.

2. @Repository is a stereotype for the persistence layer.


3. @Service is a stereotype for the service layer.

This is a good diagram to explain the hierarchy of all these notation:

image

The difference between them is, @component is used to annotate compound classes, @Repository is a marker for automatic exception translation in the persistence layer, for service layer we need to use @service.

You can refer Spring Documentation to know more.

Browse Categories

...