【问题标题】:What's the difference between how @Component and @Repository / @Service annotations are processed?@Component 和 @Repository / @Service 注解的处理方式有什么区别?
【发布时间】:2009-12-17 19:05:59
【问题描述】:

我今天在 Spring 3.0 中偶然发现了一个相当奇怪的问题:

有一个抽象类A 及其具体实现A_Impl。 A_Impl 被注释为 @Repository 并被 Spring 自动扫描(<context:component-scan> 和 <context:annotation-config/> 都在上下文中声明)。 A 和 A_Impl 部署在单独的 JAR 中(不确定这是否重要)。一切正常。

现在,我正在审查该代码,而 @Repository 在语义上似乎不太合适(所讨论的类与持久性无关)所以 - 以我无限的智慧 - 我决定将其更改为更通用的@Component。不用说,一切都搞砸了,让我看起来像个彻头彻尾的白痴。错误(在 Spring 上下文初始化期间发生)是 Spring 的 ClassPathResource.getInputStream() 方法抱怨 A 类不存在(它是,我手动检查过;加上常规类加载器发现它很好)

没有其他变化。如果我将 @Component 交换为 @Repository 上下文初始化,如果我将它们交换回来,则不会出现上述错误。 Spring documentation claims there's no difference 介于 @Component 和 @Repository 之间,这显然是一个该死的谎言 :-) 所以我想知道 - 有什么区别?

【问题讨论】:

    标签: java spring dependency-injection


    【解决方案1】:

    我一直在使用@Component,没有遇到任何问题。

    我想到的唯一一件事(虽然不是那么聪明)是你的@Component 可能不是春天的那个。例如,Tapestry 有一个以相同方式命名的注释。其他框架也可能有它。所以检查你的进口。

    【讨论】:

    • 好点,但绝对是 Spring 的@Component。如果不是这样,它根本就不会被拾取 - 但它会在这个过程中炸毁上下文。
    • 嗯。异常是“找不到类型的 .. bean”,还是另一个?
    • 不,异常是从ClassPathResource.getInputStream() 抛出的FileNotFoundException,因为类加载器无法为A.class 打开InputStream。我不太关心解决这个错误本身 - 我有理由确定这是 Spring 的错误,当我有机会并确认它时,我会逐步检查代码 - 因为我想知道如何(以及为什么) @Repository 和@Component 处理不同。
    • 这确实很奇怪。貌似@Repositry、@Controller和@Service本身都用@Component注解了,还有一个TypeFilter只注册了@Component。您能否提供整个堆栈跟踪 - 我碰巧检查了弹簧源(对于此类情况)
    • 我已将其改回@Component 并进行了干净的构建以获取堆栈跟踪,现在它可以工作了:-) 我猜它一定是一些奇怪的构建工件抛出了类加载器。感谢您的帮助。
    【解决方案2】:
    |Annotation  | Meaning                                             |
    +------------+-----------------------------------------------------+
    | @Component | generic stereotype for any Spring-managed component |
    | @Repository| stereotype for persistence layer                    |
    | @Service   | stereotype for service layer                        |
    | @Controller| stereotype for presentation layer (spring-mvc)      |
    

    从数据库连接的角度来看,@Service 和 @Repository 注释的使用很重要。

    1. 将@Service 用于所有Web 服务类型的数据库连接
    2. 将@Repository 用于所有存储的过程数据库连接

    如果您没有使用正确的注解,您可能会面临被回滚事务覆盖的提交异常。您将在压力负载测试期间看到与回滚 JDBC 事务相关的异常。

    【讨论】:

    • 有人可以澄清“数据库连接的Web服务类型”和“存储的proc数据库连接”是什么意思吗?我想知道 Satish 是否将“服务层”误解为​​指 Web 服务。
    猜你喜欢
    • 2011-10-13
    • 1970-01-01
    • 2019-01-08
    • 2013-03-09
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    相关资源
    最近更新 更多