Springの@Serviceアノテーション

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

Springの@Serviceアノテーション

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

春の@Serviceの例

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

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
	<version>5.0.6.RELEASE</version>
</dependency>
spring service annotation example
package com.scdev.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;
	}
}

以下の文章を日本語で表現する:
ただし、2つの整数を加算および減算する機能を提供する単純なJavaクラスであることに注意してください。したがって、これをサービスプロバイダと呼ぶことができます。@Serviceアノテーションで注釈を付けているため、Springコンテキストが自動的に検出でき、コンテキストからそのインスタンスを取得できます。アノテーションドリブンのSpringコンテキストを作成し、サービスクラスのインスタンスを取得するメインクラスを作成しましょう。

package com.scdev.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringMainClass {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		context.scan("com.scdev.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);
		
		//close the spring context
		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ドキュメント

コメントを残す 0

Your email address will not be published. Required fields are marked *