【问题标题】:Spring has @Component annotation, what is the real purpose of the annotations @Repository, @Service, @Controller? [duplicate]Spring有@Component注解,@Repository、@Service、@Controller这些注解的真正目的是什么? [复制]
【发布时间】:2013-03-09 13:34:28
【问题描述】:

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

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

【问题讨论】:

    标签: spring-annotations


    【解决方案1】:

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

    在 Spring 2.0 及更高版本中,@Repository 注解是 任何满足角色或原型的类(也称为数据 存储库的访问对象或 DAO)。在这个标记的用途中 是异常的自动翻译。

    Spring 2.5 引入了更多的原型注解:@Component, @Service 和 @Controller。 @Component 是任何类型的通用构造型 Spring 管理的组件。 @Repository、@Service 和 @Controller 是 @Component 的专业化用于更具体的用例,例如 例如,在持久层、服务层和表示层中, 分别。

    因此,您可以使用@Component 注释您的组件类, 但是通过使用@Repository、@Service 或@Controller 注释它们 相反,您的类更适合工具处理 或与方面相关联。例如,这些原型注解 为切入点制作理想的目标。

    因此,如果您在使用 @Component 或 @Service 之间进行选择 您的服务层,@Service 显然是更好的选择。相似地, 如上所述,@Repository 已经被支持作为标记 持久层中的自动异常转换。

    【讨论】:

    • 对我的问题的一个很好的解释,我完全理解。 Stijn Haus,非常感谢。
    猜你喜欢
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多