@Component vs @Repositoryおよび@Service in Spring
1. 前書き
このクイックチュートリアルでは、Spring Frameworkでの@Component, @Repository, @Serviceアノテーションの違いについて学習します。
参考文献:
Spring @Qualifierアノテーション
@Autowiredだけでは、依存関係を明確にするのに十分でない場合があります。 @Qualifierアノテーションを使用して、より正確に配線できます。 @Primaryも役立ちます。
2. 春の注釈
ほとんどの典型的なアプリケーションでは、データアクセス、プレゼンテーション、サービス、ビジネスなどの個別のレイヤーがあります。
そして、各層にはさまざまなBeanがあります。 簡単に言えば、それらを自動的に検出するには、Spring uses classpath scanning annotationsです。
次に、各BeanをApplicationContextに登録します。
これらのアノテーションのいくつかの概要は次のとおりです。
-
@Componentは、Springが管理するコンポーネントの一般的なステレオタイプです。
-
@Serviceは、サービスレイヤーでクラスに注釈を付けます
-
@Repositoryは、データベースリポジトリとして機能する永続層でクラスに注釈を付けます
これらのアノテーションについては、すでにextended articleがあります。 そのため、両者の違いにのみ焦点を当てます。
3. 何が違うの?
The major difference between these stereotypes is they are used for different classification.自動検出用にクラスに注釈を付ける場合は、それぞれのステレオタイプを使用する必要があります。
それでは、それらについて詳しく見ていきましょう。
3.1. @Component
We can use @Component across the application to mark the beans as Spring’s managed components。 Springは、Beanを取得して@Component に登録するだけで、一般に@Serviceと@Repositoryを検索しません。
それら自体に@Componentの注釈が付けられているため、ApplicationContextに登録されます。
@Component
public @interface Service {
}
@Component
public @interface Repository {
}
@Serviceと@Repositoryは、@Componentの特殊なケースです。 技術的には同じですが、異なる目的に使用します。
3.2. @Repository
@Repository’s job is to catch persistence specific exceptions and rethrow them as one of Spring’s unified unchecked exception。
このSpringはPersistenceExceptionTranslationPostProcessorを提供します。これには、アプリケーションコンテキストに追加する必要があります。
このBeanポストプロセッサは、@Repository.でアノテーションが付けられたBeanにアドバイザを追加します
3.3. @Service
We mark beans with @Service to indicate that it’s holding the business logic。 したがって、サービスレイヤーで使用する以外に特別なことはありません。
4. 結論
In this write-up, we learned about the differences between @Component, @Repository, @Service annotations。 それぞれの注釈を、それらの使用分野で個別に調べました。
結論として、レイヤーの規則に基づいてアノテーションを選択することは常に良い考えです。