java – Spring中@Service注释的功能

这是一种“什么是@Service注释?”问题,但另一种方法.因为,我不确定这里发生了什么:

我有一个控制器类:

@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");
    }
}

配置有两个版本.

> SomeBean在.xml中配置:

喜欢:

< bean id="someBean" class="package.SomeBean"></bean>

> SomeBean被注释为服务(在它没有的第一个服务中):

喜欢:

@Service
public class SomeBean{...}

>请注意,在这两种情况下,注射等没有任何问题.在这两种情况下,客户端都成功订阅,发送消息,并处理消息.

唯一的区别是:

>当SomeBean具有@Service注释时,它成功响应客户端,但是当它没有时,客户端不会收到响应消息,尽管没有任何异常.

这是一个问题:

>在这种情况下,@ Service实际上做了什么?有人可以解释一下这里发生了什么吗?

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

主要区别在于使用@Service注释的类是在类路径扫描期间自动检测的候选者.使用注释驱动的依赖注入,您不需要在xml配置中将每个Java类声明为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.

点赞