分派器Servlet无法映射到WebSocket请求 [英] Dispatcher-servlet cannot map to websocket requests
问题描述
我正在开发一个以Spring为主要框架的Java Web应用程序(特别使用Spring核心,Spring mvc,Spring安全性,Spring数据,Spring Websocket).
I'm developing a Java webapp with Spring as the main framework (Spring core, Spring mvc, Spring security, Spring data, Spring websocket are notably used).
在这样的Spring上下文中声明消息代理,为该上下文提供了SimpMessagingTemplate bean:
Declaring a message-broker in a Spring context like this provides a SimpMessagingTemplate bean to the context :
<websocket:message-broker>
<websocket:stomp-endpoint path="/stomp">
<websocket:sockjs/>
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic,/queue"/>
</websocket:message-broker>
我必须将此标记放在我的根上下文(applicationContext.xml)中,否则在该根上下文中声明的服务无法通过websocket向用户发送通知(因为他们需要SimpMessagingTemplate).
I have to put this tag in my root context (applicationContext.xml), otherwise services declared in that root context cannot send notifications to users via websocket (because they need the SimpMessagingTemplate).
问题是,如果我将此标签放在根上下文中,则客户端在订阅websocket时会收到404.而且,如果我将标记放在调度程序servlet中,则根上下文中的服务将无法发送通知,因为它们将需要SimpMessagingTemplate(但仅在子调度程序servlet上下文中可用).
The thing is, if I put this tag in the root context, clients get a 404 when they subscribe to websocket. And if I put the tag in the dispatcher-servlet, then services in the root context cannot send notifications since they would need the SimpMessagingTemplate (but it is only available in the child dispatcher-servlet context).
有没有一种方法可以将调度程序servlet绑定到代理?两次声明该bean不是正确的解决方案.
Is there a way to "bind" the dispatcher-servlet to the broker ? Declaring the bean twice is not a correct solution.
此问题与 Spring相同:如何公开SimpMessagingTemplate bean到根上下文?,但从另一个角度看(在根上下文中而不是在dispatcher-servlet中声明websocket)
This issue is the same as Spring : how to expose SimpMessagingTemplate bean to root context ? but looking from another angle (declaring websocket in the root context instead of in the dispatcher-servlet)
推荐答案
我发现了一个肮脏的解决方案.我不喜欢它,但是由于缺少SO以及现任和前任同事的答案,我不得不继续进行该项目并实施了一个肮脏的修复程序.
I found a dirty solution. I don't like it, but given the lack of answers on SO as well as from current and former colleagues, I had to go forward with the project and implemented a dirty fix.
肮脏的修补程序是对Controller和Scheduled类中的Autowire
SimpMessagingTemplate
(全部由声明websocket tag
的dispatcher-servlet
扫描),并将SimpMessagingTemplate
作为参数传递给服务方法(在root context
中声明).
The dirty fix is to Autowire
the SimpMessagingTemplate
in Controller and Scheduled classes (all scanned by the dispatcher-servlet
, where the websocket tag
is declared), and to pass the SimpMessagingTemplate
as a parameter to service methods (declared in the root context
).
此解决方案不是透明的(理想情况下,SimpMessagingTemplate
应该直接自动连接到服务中),但肯定可以解决问题.
This solution is not transparent (the SimpMessagingTemplate
should be autowired directly in services ideally) but it definitely fixes the problem.
这篇关于分派器Servlet无法映射到WebSocket请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!