Spring @Service批注
时间:2020-02-23 14:36:01 来源:igfitidea点击:
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.theitroad.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.theitroad.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringMainClass {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.theitroad.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, 2016 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 2016]; root of context hierarchy Addition of 1 and 2 = 3 Subtraction of 2 and 1 = 1 Jun 05, 2016 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 2016]; root of context hierarchy
如果您注意到我们的MathService类,则我们已将服务名称定义为" ms"。
我们也可以使用该名称获取MathService的实例。
在这种情况下,输出将保持不变。
但是,我们将必须使用显式强制转换。
MathService ms = (MathService) context.getBean("ms");

