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 类,提供了添加和减去两个整数的功能。因此,我们可以称它为服务提供者。我们用 @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