知識庫 / Spring RSS 訂閱

Spring 中的 @Component、@Repository 和 @Service 區別與用法

Spring
HongKong
10
01:44 PM · Dec 06 ,2025

1. 引言

在本快速教程中,我們將學習 Spring 框架中 @Component, @Repository, @Service 標註之間的區別。

2. Spring 註解

在大多數典型應用中,我們有明確的分層結構,例如數據訪問、呈現、服務、業務等。

此外,在每個層級中,我們有各種 Bean。為了自動檢測這些 Bean,Spring 使用 classpath 掃描註解

然後它會註冊每個 Bean 到 ApplicationContext 中。

以下是這些註解的快速概述:

  • @Component 是一個通用的 Stereotype,用於任何 Spring 管理的組件。
  • @Service 註解服務層中的類。
  • @Repository 註解持久層中的類,它將充當數據庫倉庫。

我們已經有一個關於這些註解的擴展文章,因此我們將重點放在它們之間的差異上。

3. 區別是什麼?

這些刻板印象的主要區別在於它們被用於不同的分類。當我們為自動檢測對類進行標註時,應使用相應的刻板印象。

現在我們來更詳細地瞭解一下它們。

3.1. @Component

我們可以使用 @Component 在整個應用程序中標記 Bean 作為 Spring 的管理組件。Spring 只會拾取並註冊帶有 @Component 註解的 Bean,不會查找 @Service@Repository 註解。

它們註冊在 ApplicationContext 中,因為它們使用了 @Component 註解。

@Component
public @interface Service {
}
@Component
public @interface Repository {
}

@Service@Repository@Component 的特殊情況。它們在技術上相同,但我們使用它們用於不同的目的。

3.2. @Repository

@Repository 的作用是捕獲持久化相關的異常並將其重新拋出為 Spring 的統一未檢查異常。

為此,Spring 提供 PersistenceExceptionTranslationPostProcessor,我們需要將其添加到應用程序上下文(如果使用 Spring Boot,則已包含該處理器):

<bean class=
  "org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

此 Bean 屬性處理器會為任何帶有 @Repository 註解的 Bean 添加一個顧問。

3.3. @Service

我們使用 @Service 註解標記 Bean,以指示它們持有業務邏輯。除了在服務層中使用之外,此註解沒有其他特殊用途。

4. 結論

在本文中,我們學習了 @Component, @Repository, @Service 註解之間的區別。我們分別研究了每個註解的應用領域,以加深理解。

總而言之,選擇註解時應遵循其層級約定始終是一個明智的選擇。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.