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

后端 未结 29 2198
时光说笑
时光说笑 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:06

    Spring 2.5 introduces further stereotype annotations: @Component, @Service and @Controller. @Component serves as a generic stereotype for any Spring-managed component; whereas, @Repository, @Service, and @Controller serve as specializations of @Component for more specific use cases (e.g., in the persistence, service, and presentation layers, respectively). What this means is that you can annotate your component classes with @Component, but by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts. Of course, it is also possible that @Repository, @Service, and @Controller may carry additional semantics in future releases of the Spring Framework. Thus, if you are making a decision between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated above, @Repository is already supported as a marker for automatic exception translation in your persistence layer.

    @Component – Indicates a auto scan component.
    @Repository – Indicates DAO component in the persistence layer.
    @Service – Indicates a Service component in the business layer.
    @Controller – Indicates a controller component in the presentation layer.
    

    reference :- Spring Documentation - Classpath scanning, managed components and writing configurations using Java

提交回复
热议问题