我基本上是按照文档中提供的指南配置Spring中的Websockets。
我目前正在尝试像“从任何地方发送消息”一节中所述那样,从服务器向客户端发送消息。
按照示例,您可以自动装配一个名为SimpMessagingTemplate的类。
@Controller
public class GreetingController {
private SimpMessagingTemplate template;
@Autowired
public GreetingController(SimpMessagingTemplate template) {
this.template = template;
}
@RequestMapping(value="/greetings", method=POST)
public void greet(String greeting) {
String text = "[" + getTimestamp() + "]:" + greeting;
this.template.convertAndSend("/topic/greetings", text);
}
}
然而,我的当前项目无法找到bean“SimpMessagingTemplate”。(Intellij:“无法自动装配。找不到SimpMessagingTemplate类型的bean。”)
我已经查看了互联网上的几个示例,但我无法找到如何让Spring创建SimpMessagingTemplate实例的方法。如何进行自动装配?
编辑:
我决定发送一些更多的背景信息。这是我的当前websocket配置:
<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-4.0.xsd">
<!-- TODO properties to be read from a properties file -->
<websocket:message-broker application-destination-prefix="/app">
<websocket:stomp-endpoint path="/new_session" >
<websocket:sockjs/>
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic"/>
</websocket:message-broker>
</beans>
Websocket与此控制器配合使用
@Controller
public class SessionController {
private static final Logger log = LoggerFactory.getLogger(SessionController.class);
@MessageMapping("/new_session")
@SendTo("/topic/session")
public SessionStatus newSession(Session session) throws Exception {
Thread.sleep(3000); // simulated delay
log.info("Response sent !!");
return new SessionStatus("StatusReport, " + session.toString() + "!");
}
}
我不确定如何让这个工作起来
public class SessionController {
private static final Logger log = LoggerFactory.getLogger(SessionController.class);
private SimpMessagingTemplate template;
@Autowired
public SessionController(SimpMessagingTemplate template) {
this.template = template;
}
}
由于找不到豆子“SimpMessagingTemplate模板”,Spring文档没有提供更多有关此事的细节。
编辑:github中的工作代码示例。