簡體   English   中英

如何處理@Component和@Repository / @Service注釋之間的區別是什么?

[英]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/>都在上下文中聲明)。 AA_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注釋很重要。

  1. @Service用於所有Web服務類型的數據庫連接
  2. @Repository用於所有存儲的proc數據庫連接

如果您不使用正確的注釋,則可能會遇到由回滾事務覆蓋的提交異常。 您將在壓力負載測試期間看到與回滾JDBC事務相關的異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM