Spring @Service 注解

Spring @Service 注釋是 @Component 注釋的特例。Spring Service 注釋僅適用於類別。它用於將類別標記為服務提供者。

Spring @Service 注釋

Spring @Service 注釋用於提供某些業務功能的類別。當使用基於注釋的配置和類路徑掃描時,Spring 上下文將自動檢測這些類別。

Spring @Service 範例

讓我們創建一個簡單的 Spring 應用程序,我們將在其中創建一個 Spring 服務類別。在 Eclipse 中創建一個簡單的 Maven 項目,並添加以下 spring core 依賴項。

<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 類別,提供了將兩個整數相加和相減的功能。因此我們可以稱它為服務提供者。我們已經用 @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