Spring中@Service注解的功能

The functionality of @Service annotation in Spring

这是一种"what is @Service annotation?"问题,但采用了另一种方法。因为,我不确定这里发生了什么:

我有一个控制器class:

@Controller
public class GreetingController {
    @Autowired
    SomeBean someBean;

    @MessageMapping("/msg")
    public String msg() {
        someBean.handleMsg();
        return "";
    }
}

我尝试从 someBean.handleMsg 中向目标发送响应。 像这样的事情:

public class SomeBean {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    public handleMsg() {
        messagingTemplate.convertAndSend("/topic/someTopic", "Response");
    }
}

两个版本的配置

  1. SomeBean配置在.xml:

喜欢:

< bean id="someBean" class="package.SomeBean"></bean>
  1. SomeBean 被注释为 service(在第一个它没有):

喜欢:

@Service
public class SomeBean{...}

只有 不同是:

这里是问题:

从技术角度来看,基于 @Service 和 xml 的配置之间几乎没有区别。这两种方法都用于将 Java classes 声明为 Spring bean,这些 bean 在基于 Spring 的应用程序中被管理和用于依赖注入。

主要区别在于,用 @Service 注释的 class 是 class 路径扫描期间自动检测的候选对象。使用注释驱动的依赖注入,您不需要在 xml 配置中将每个 Java class 声明为 Spring bean。

这就是 javadoc 所说的:

Indicates that an annotated class is a "Service", originally defined by Domain-Driven Design (Evans, 2003) as "an operation offered as an interface that stands alone in the model, with no encapsulated state."

May also indicate that a class is a "Business Service Facade" (in the Core J2EE patterns sense), or something similar. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.

This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.

@Service:这告诉Spring它是一个服务class,你可能有@Transactional等服务层相关的注释所以Spring 将其视为服务组件。

@Service@Component 的特化。假设 bean class 名称是 "CustomerService",因为你没有选择 XML bean 配置方式,所以你用 @Component 注释 bean 以表明它是一个 Bean。所以你可以用 :

检索这个 bean
CustomerService cust = (CustomerService)context.getBean("customerService");

默认情况下,Spring 会将组件的第一个字符小写 - 从“CustomerService”到“customerService”。您可以使用名称“customerService”检索此组件。

就像 @Component 注释一样,如果您使用 @Service 注释,您可以像这样为其提供特定的 bean 名称:

@Service("myBeanName")
public class CustomerService{

您可以通过以下方式获取 bean 对象:

CustomerService cust = (CustomerService)context.getBean("myBeanName");