gpt4 book ai didi

spring-annotations - Spring有@Component注解,@Repository、@Service、@Controller注解的真正目的是什么?

转载 作者:行者123 更新时间:2023-12-03 20:51:37 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





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

(29 个回答)


8年前关闭。




我已经使用 Spring 框架开发了几年的 Web 应用程序。最近,我团队的一个新生问了我一个问题,Spring有@Component注释,注释的真正用途是什么@Repository , @Service , @Controller ?我试图给他的答案是它们之间没有区别,只是为了识别java Bean的类型。如你所知,我的解释缺乏说服力,他没有买。

所以我想问一个问题,注解的真正目的是什么@Repository , @Service , @Controller ?这些注释之间的真正区别是什么?

最佳答案

以前有人问过这个问题:What's the difference between @Component, @Repository & @Service annotations in Spring?

In Spring 2.0 and later, the @Repository annotation is a marker for any class that fulfills the role or stereotype (also known as Data Access Object or DAO) of a repository. Among the uses of this marker is the automatic translation of exceptions.

Spring 2.5 introduces further stereotype annotations: @Component, @Service, and @Controller. @Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.

Therefore, 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.

Thus, if you are choosing 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.

关于spring-annotations - Spring有@Component注解,@Repository、@Service、@Controller注解的真正目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15523855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com