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

后端 未结 29 2165
时光说笑
时光说笑 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 01:04

    Spring provides four different types of auto component scan annotations, they are @Component, @Service, @Repository and @Controller. Technically, there is no difference between them, but every auto component scan annotation should be used for a special purpose and within the defined layer.

    @Component: It is a basic auto component scan annotation, it indicates annotated class is an auto scan component.

    @Controller: Annotated class indicates that it is a controller component, and mainly used at the presentation layer.

    @Service: It indicates annotated class is a Service component in the business layer.

    @Repository: You need to use this annotation within the persistence layer, this acts like database repository.

    One should choose a more specialised form of @Component while annotating their class as this annotation may contain specific behavior going forward.

提交回复
热议问题