Spring Component注釈は、クラスをComponentとして示すために使用されます。これは、Springフレームワークが、注釈ベースの構成とクラスパスのスキャンが使用されると、これらのクラスを依存性の注入のために自動的に検出することを意味します。
Spring Component
簡単に言えば、Componentはいくつかの操作に責任を持ちます。Springフレームワークは、クラスをComponentとしてマークする際に使用する3つの他の特定の注釈を提供しています。
Service
:クラスがいくつかのサービスを提供することを示します。私たちのユーティリティクラスはServiceクラスとしてマークされることがあります。Repository
:この注釈は、クラスがCRUD操作を処理することを示します。通常は、データベーステーブルを扱うDAOの実装と一緒に使用されます。Controller
:主にWebアプリケーションまたはREST Webサービスと一緒に使用され、クラスがフロントコントローラーであり、ユーザーのリクエストを処理し、適切な応答を返す責任があることを指定します。
注意してください、これらの4つの注釈はすべてorg.springframework.stereotype
パッケージにあり、spring-context
jarの一部です。
Springコンポーネントの例
Spring Component注釈の使用と、注釈ベースの構成とクラスパススキャンによるSpringの自動検出を示す非常にシンプルなSpring Mavenアプリケーションを作成しましょう。Mavenプロジェクトを作成し、次のSpringコア依存関係を追加します。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
これで、Springフレームワークのコア機能を取得するのに必要なものがすべて揃いました。単純なコンポーネントクラスを作成し、@Component
注釈でマークします。
package com.journaldev.spring;
import org.springframework.stereotype.Component;
@Component
public class MathComponent {
public int add(int x, int y) {
return x + y;
}
}
これで、注釈ベースのSpringコンテキストを作成し、MathComponent
ビーンを取得できます。
package com.journaldev.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringMainClass {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.journaldev.spring");
context.refresh();
MathComponent ms = context.getBean(MathComponent.class);
int result = ms.add(1, 2);
System.out.println("Addition of 1 and 2 = " + result);
context.close();
}
}
上記のクラスを通常のJavaアプリケーションとして実行するだけで、コンソールに以下の出力が表示されます。
Jun 05, 2018 12:49:26 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Tue Jun 05 12:49:26 IST 2018]; root of context hierarchy
Addition of 1 and 2 = 3
Jun 05, 2018 12:49:26 PM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Tue Jun 05 12:49:26 IST 2018]; root of context hierarchy
Springの力を感じましたか? 私たちのコンポーネントをSpringコンテキストにインジェクトするために何もする必要はありませんでした。以下の画像は、Springコンポーネントの例プロジェクトのディレクトリ構造を示しています。 コンポーネント名を指定して、同じ名前を使用してSpringコンテキストから取得することもできます。
@Component("mc")
public class MathComponent {
}
MathComponent ms = (MathComponent) context.getBean("mc");
雖然私は@Component
アノテーションをMathComponentと共に使用していますが、実際にはサービスクラスであり、@Service
アノテーションを使用する必要があります。結果は変わりません。
プロジェクトは当社のGitHubリポジトリからチェックアウトできます。
参照:APIドキュメント
Source:
https://www.digitalocean.com/community/tutorials/spring-component