![](/img/trans.png)
[英]What's the difference between @Component, @Repository & @Service annotations in Spring?
[英]What's the difference between how @Component and @Repository / @Service annotations are processed?
今天我在Spring 3.0中偶然發現了一個相當奇怪的問題:
有一個抽象類A
及其具體實現A_Impl
。 A_Impl
被注釋為@Repository
和是自動掃描由彈簧( <context:component-scan>
和<context:annotation-config/>
都在上下文中聲明)。 A
和A_Impl
部署在單獨的JAR中(不確定是否重要)。 一切正常。
現在,我正在審查代碼, @Repository
在語義上似乎不太合適(這個類與持久性無關)所以 - 在我的無限智慧中 - 我決定將其更改為更通用的@Component
。 毋庸置疑,一切都爆發了,讓我看起來像一個完全白痴。 錯誤(在Spring上下文初始化期間發生)是Spring的ClassPathResource.getInputStream()
方法抱怨A
類不存在(它是,我已經手動檢查;加上常規類加載器發現它很好)
沒有其他改變 。 如果我將@Component
交換為@Repository
上下文初始化,如果我將它們交換回來,則不會出現上述錯誤。 Spring文檔聲稱沒有差別之間@Component
和@Repository
這顯然是一個該死的謊言:-)所以我想- 有什么區別?
我一直在使用@Component
沒有麻煩。
我想到的唯一一件事(盡管不是那么聰明的人)可能是你的@Component
可能不是春天的。 例如,Tapestry有一個以相同方式命名的注釋。 其他框架也可能有它。 所以檢查你的進口。
|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
用於所有Web服務類型的數據庫連接 @Repository
用於所有存儲的proc數據庫連接 如果您不使用正確的注釋,則可能會遇到由回滾事務覆蓋的提交異常。 您將在壓力負載測試期間看到與回滾JDBC事務相關的異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.