Spring WebSockets XML 配置不提供 brokerMessagingTemplate

Spring WebSockets XML configuration not providing brokerMessagingTemplate

我正在尝试将使用 STOMP 的 WebSockets 支持添加到使用 XML 配置的 Spring MVC 应用程序中。到目前为止,一切进展顺利,我已经设法让 WebSockets 服务器监听,并且 stomp.js 可以连接到它并发送消息和接收响应。

我还没有设法开始工作的是支持服务器向客户端发送任意消息,这些消息不是对从客户端收到的消息的响应。这意味着到目前为止,这实际上只是 REST 的一个更复杂的版本,并不太有用。

我的 XML 配置如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:websocket="http://www.springframework.org/schema/websocket"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd">

  <websocket:message-broker>
    <websocket:stomp-endpoint path="/api/websocket/stomp" allowed-origins="*">
    </websocket:stomp-endpoint>

    <websocket:simple-broker prefix="/topic,/queue" />

    <websocket:message-converters>
        <bean class="org.springframework.messaging.converter.MappingJackson2MessageConverter">
            <property name="objectMapper" ref="objectMapper" />
        </bean>
    </websocket:message-converters>
   </websocket:message-broker>

  <bean class="uk.co.grahamcox.webapp.DebugController">
    <constructor-arg name="clock" ref="clock" />
    <constructor-arg name="template" ref="brokerMessagingTemplate" />
  </bean>
</beans>

(DebugController 是一个 class,它有一个单一的方法来 return 服务器时间,作为 REST 和 WS 处理程序都可以正常工作)

启动时我得到:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'brokerMessagingTemplate' is defined

令人沮丧的是 IntelliJ 为我自动完成了 "brokerMessagingTemplate" 参考,我可以点击它进入 AbstractMessageBrokerConfiguration 中的 @Bean 定义。

我假设我在 XML 中缺少一些配置来完成这项工作,但我无法在文档中找到它是什么。

有什么建议吗?

support for the server to send arbitrary messages to the client that aren't responses to one received from the client.

向客户发送消息的一种方法是让他们首先订阅一个主题——确保理解 "application destination prefixes" 和 "broker prefixes" 之间的区别。在这种特殊情况下,您希望客户端订阅代理目的地,然后您的服务器可以随时向所有这些客户端发送消息。

了解这一点的最佳方法是查看 flow of messages in the reference documentation

要发送这些消息,您的应用程序代码需要一个消息传递模板。

您可以通过将表单 bean 名称切换为实际 bean 类型来修复您的代码示例 SimpMessagingTemplate

  <bean class="uk.co.grahamcox.webapp.DebugController">
    <constructor-arg name="clock" ref="clock" />
    <constructor-arg name="template" class="org.springframework.messaging.simp.SimpMessagingTemplate" />
  </bean>

reference documentation mentions that bean name but it seems that it's not registered with this name when using the XML configuration. Feel free to create a JIRA issue 改进这个。