What's the difference between @Component, @Repository & @Service annotations in Spring?

后端 未结 29 2719
时光说笑
时光说笑 2020-11-22 00:33

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

29条回答
  •  眼角桃花
    2020-11-22 00:50

    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:

    1. @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.
    2. @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.
    3. @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.

提交回复
热议问题