Can @Component, @Repository and @Service annotations be used interchangeably in Spring or do they provide any particular functionality besides acting as a notation device?>
Technically @Controller
, @Service
, @Repository
are all same. All of them extends @Component
.
From the Spring source code:
Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.
We can directly use @Component
for each and every bean, but for better understanding and maintainability of a large application, we use @Controller
, @Service
, @Repository
.
Purpose of each annotation:
@Controller
-> Classes annotated with this, are intended to receive a request from the client side. The first request comes to the Dispatcher Servlet, from where it passes the request to the particular controller using the value of @RequestMapping
annotation.@Service
-> Classes annotated with this, are intended to manipulate data, that we receive from the client or fetch from the database. All the manipulation with data should be done in this layer.@Repository
-> Classes annotated with this, are intended to connect with database. It can also be considered as DAO(Data Access Object) layer. This layer should be restricted to CRUD (create, retrieve, update, delete) operations only.
If any manipulation is required, data should be sent be send back to @Service layer.If we interchange their place(use @Repository
in place of @Controller
), our application will work fine.
The main purpose of using three different @annotations
is to provide better Modularity to the Enterprise application.