轉載
原文:https://www.javaroad.cn/articles/1693
官方文檔:
https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-stereotype-annotations
在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作為持久層中自動異常轉換的标記。

下面是網上贊同比較多的解釋
@ Component,@ Repository,@ Controller和@Service之間的差異
@Component
這是一個通用的構造型注釋,表明該類是一個spring元件。
@Component有什麼特别之處
context:component-scan only掃描@Component并且一般不尋找@Controller,@Service和@Repository。掃描它們是因為它們本身用@Component注釋。
隻需看看@Controller,@Service和@Repository注釋定義:
@Component
public @interface Service {
….
}
@Component
public @interface Repository {
….
}
@Component
public @interface Controller {
…
}
是以,說@Controller,@Service和@Repository是特殊類型的@Componentannotation.context:component-scan并沒有錯,并将它們的下一個類注冊為bean,就好像它們是用@Component注釋一樣。
它們被掃描,因為它們本身用注釋注釋為@Component。如果我們定義自己的自定義注釋并使用@Component進行注釋,那麼它也将被掃描 context:component-scan
@Repository
這是為了表明該類定義了一個資料存儲庫。
@Repository有什麼特别之處?
除了指出這是一個基于注釋的配置之外,@Repository的工作是捕獲平台特定的異常,并将它們重新抛出為Spring的統一未經檢查的異常之一。為此,我們提供了3886827546,我們需要在Spring的應用程式上下文中添加如下:
這個bean後處理器為任何帶有@Repository注釋的bean添加了一個顧問程式,以便捕獲任何特定于平台的異常,然後将其作為Spring未經檢查的資料通路異常之一重新抛出。
@Controller
@Controller annotation訓示特定類充當控制器的角色。 [email protected]充當帶注釋的類的構造型,訓示其角色。
@Controller有什麼特别之處?
我們無法将此注釋與其他任何類似的@Service或@Repository切換,即使它們看起來相同。排程程式掃描用@Controller注釋的類,并檢測其中的@RequestMapping個注釋。我們隻能使用@[email protected]注釋類。
@Service
@Services保留存儲庫層中的業務邏輯和調用方法。
@Service有什麼特别之處?
除了它用于表明它持有業務邏輯這一事實之外,這個注釋沒有明顯的特點,但是誰知道,spring可能在未來增加一些額外的特殊功能。
還有什麼?
與上面類似,将來Spring可能會根據它們的分層約定選擇為@Service,@Controller和@Repository添加特殊功能。是以,尊重慣例并将其與層一緻使用始終是一個好主意。