問題描述
可以@Component
, @Repository
和 @Service
注解在 Spring 中可以互換使用,或者它們是否提供除了作為注解設備之外的任何特定功能?
Can @Component
, @Repository
and @Service
annotations be used interchangeably in Spring or do they provide any particular functionality besides acting as a notation device?
換句話說,如果我有一個 Service 類并且我將注解從 @Service
更改為 @Component
,它的行為方式是否仍然相同?
In other words, if I have a Service class and I change the annotation from @Service
to @Component
, will it still behave the same way?
或者注解也會影響類的行為和功能?
Or does the annotation also influence the behavior and functionality of the class?
推薦答案
來自 Spring 文檔:
@Repository
注釋是任何滿足存儲庫的角色或原型(也稱為數據訪問對象)或 DAO).該標記的用途之一是自動翻譯例外,如 異常翻譯.
The
@Repository
annotation is a marker for any class that fulfils the role or stereotype of a repository (also known as Data Access Object or DAO). Among the uses of this marker is the automatic translation of exceptions, as described in Exception Translation.
Spring 提供了更多的原型注解:@Component
、@Service
、和 @Controller
.@Component
是任何類型的通用構造型Spring 管理的組件.@Repository
、@Service
和 @Controller
是@Component
的特化,用于更具體的用例(在分別是持久層、服務層和表示層).因此,您可以使用 @Component
注釋您的組件類,但是,通過使用 @Repository
、@Service
或 @Controller
注釋它們相反,您的類更適合工具處理或與方面相關聯.
Spring provides further stereotype annotations: @Component
, @Service
,
and @Controller
. @Component
is a generic stereotype for any
Spring-managed component. @Repository
, @Service
, and @Controller
are
specializations of @Component
for more specific use cases (in the
persistence, service, and presentation layers, respectively).
Therefore, you can annotate your component classes with @Component
,
but, by annotating them with @Repository
, @Service
, or @Controller
instead, your classes are more properly suited for processing by tools
or associating with aspects.
例如,這些原型注解為切入點制作理想的目標.@Repository
、@Service
和@Controller
還可以在未來版本的春天框架.因此,如果您在使用@Component
或 @Service
為您的服務層,@Service
顯然是更好的選擇.同樣,如前所述,@Repository
已經支持作為自動異常翻譯的標記持久層.
For example, these stereotype annotations
make ideal targets for pointcuts. @Repository
, @Service
, and
@Controller
can also carry additional semantics in future releases of
the Spring Framework. Thus, if you are choosing between using
@Component
or @Service
for your service layer, @Service
is clearly the
better choice. Similarly, as stated earlier, @Repository
is already
supported as a marker for automatic exception translation in your
persistence layer.
注釋 | 意義 |
---|---|
@Component | 任何 Spring 管理組件的通用構造型 |
@Repository | 持久層的原型 |
@Service | 服務層的原型 |
@Controller | 表示層的原型(spring-mvc) |
這篇關于@Component、@Repository 和 @Repository 有什么區別?Spring中的@Service注釋?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!