Spring @Service 注释

Spring @Service 注释是 @Component注释的专业化。 Spring Service 注释只能应用于类,用于标记类作为服务提供商。

春天服务评论

Spring @Service 注释用于提供某些业务功能的类别. Spring 语境在使用注释式配置和类路径扫描时会自动检测这些类别。

春天服务例子

让我们创建一个简单的春季应用程序,在那里我们将创建一个春季服务类,在Eclipse中创建一个简单的maven项目,并添加以下春季核心依赖性。

1<dependency>
2    <groupId>org.springframework</groupId>
3    <artifactId>spring-context</artifactId>
4    <version>5.0.6.RELEASE</version>
5</dependency>

Our final project structure will look like below image. spring service annotation example Let's create a service class.

 1package com.journaldev.spring;
 2
 3import org.springframework.stereotype.Service;
 4
 5@Service("ms")
 6public class MathService {
 7
 8    public int add(int x, int y) {
 9    	return x + y;
10    }
11    
12    public int subtract(int x, int y) {
13    	return x - y;
14    }
15}

请注意,这是一个简单的Java类,它提供了添加和扣除两个整数的功能,所以我们可以称之为服务提供商,我们已经用 @Service 注释了它,以便春天文本可以自动检测它,我们可以从文本中获取它的实例。

 1package com.journaldev.spring;
 2
 3import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 4
 5public class SpringMainClass {
 6
 7    public static void main(String[] args) {
 8    	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
 9    	context.scan("com.journaldev.spring");
10    	context.refresh();
11
12    	MathService ms = context.getBean(MathService.class);
13
14    	int add = ms.add(1, 2);
15    	System.out.println("Addition of 1 and 2 = " + add);
16
17    	int subtract = ms.subtract(2, 1);
18    	System.out.println("Subtraction of 2 and 1 = " + subtract);
19    	
20    	//close the spring context
21    	context.close();
22    }
23
24}

只需将类作为Java应用程序执行,它将产生以下输出。

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

如果您注意到我们的 MathService 类,我们将服务名称定义为ms。我们也可以使用这个名称获得MathService的实例。

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

这是一个快速的春季 @Service 注释的例子。

您可以从我们的 GitHub 存储库下载示例项目代码。

引用: API Doc

Published At
Categories with 技术
Tagged with
comments powered by Disqus