我今天偶然发现了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
上下文初始化,如果我将它们交换回来,则不会出现上述错误。 @Component
和@Repository
之间的Spring documentation claims there's no difference显然是一个该死的谎言:-)所以我想知道 - 的区别是什么?
答案 0 :(得分:4)
我一直在使用@Component
而没有麻烦。
我认为唯一的事情(虽然不是那么聪明)可能是你的@Component
可能不是春天的。例如,Tapestry有一个以相同方式命名的注释。其他框架也可能有它。所以检查你的进口。
答案 1 :(得分:0)
|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
注释的使用非常重要。
@Service
@Repository
如果您不使用正确的注释,则可能会遇到由回滚事务覆盖的提交异常。您将在压力负载测试期间看到与回滚JDBC事务相关的异常。