Springの@Serviceアノテーション

Spring @Serviceアノテーションは、@Componentアノテーションの特殊化です。Springの@Serviceアノテーションは、クラスにのみ適用できます。これはクラスをサービスプロバイダとしてマークするために使用されます。

Spring @Serviceアノテーション

Spring @Serviceアノテーションは、いくつかのビジネス機能を提供するクラスと共に使用されます。Springのコンテキストは、アノテーションベースの設定とクラスパススキャンが使用される場合に、これらのクラスを自動検出します。

Spring @Serviceの例

シンプルなSpringアプリケーションを作成しましょう。Springサービスクラスを作成します。EclipseでシンプルなMavenプロジェクトを作成し、次のSpringコアの依存関係を追加します。

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
	<version>5.0.6.RELEASE</version>
</dependency>

最終的なプロジェクト構造は以下の画像のようになります。サービスクラスを作成しましょう。

package com.journaldev.spring;

import org.springframework.stereotype.Service;

@Service("ms")
public class MathService {

	public int add(int x, int y) {
		return x + y;
	}
	
	public int subtract(int x, int y) {
		return x - y;
	}
}

クラスは単純なJavaクラスであり、2つの整数を追加および減算する機能を提供します。したがって、これをサービスプロバイダーと呼べます。 @Serviceアノテーションで注釈を付けています。これにより、Springコンテキストが自動検出し、コンテキストからインスタンスを取得できます。メインクラスを作成しましょう。そこで、アノテーション駆動のSpringコンテキストを作成し、サービスクラスのインスタンスを取得します。

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();

		MathService ms = context.getBean(MathService.class);

		int add = ms.add(1, 2);
		System.out.println("Addition of 1 and 2 = " + add);

		int subtract = ms.subtract(2, 1);
		System.out.println("Subtraction of 2 and 1 = " + subtract);
		
		// Springコンテキストを閉じます
		context.close();
	}

}

Javaアプリケーションとしてクラスを実行するだけで、次の出力が生成されます。

Jun 05, 2018 3:02:05 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Tue Jun 05 15:02:05 IST 2018]; root of context hierarchy
Addition of 1 and 2 = 3
Subtraction of 2 and 1 = 1
Jun 05, 2018 3:02:05 PM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Tue Jun 05 15:02:05 IST 2018]; root of context hierarchy

MathServiceクラスを見ると、「ms」というサービス名を定義しています。この名前を使用してMathServiceのインスタンスを取得することもできます。この場合でも、出力は同じです。ただし、明示的なキャストを使用する必要があります。

MathService ms = (MathService) context.getBean("ms");

これで、Spring @Serviceアノテーションの簡単な例が終わりました。

サンプルプロジェクトのコードを当社のGitHubリポジトリからダウンロードできます。

参考:APIドキュメント

Source:
https://www.digitalocean.com/community/tutorials/spring-service-annotation