The*_*heo 5 java spring annotations stomp autowired
我正在构建一个使用Stomp通过websockets代理消息的应用程序.我试图从服务器向客户端发送消息,而无需来自应用程序的任何位置的请求.我在网上找到两个单独的选择,用于从应用程序的任何位置发送消息
第一个是在Websocket文档中找到的.第20.4.5节:
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
@Controller
public class GreetingController {
@Autowired
private SimpMessagingTemplate template;
@RequestMapping(value="/greeting", method=POST)
public void greet(String greeting) {
String text = "[" + getTimeStamp() + "]:" + greeting;
this.template.convertAndSend("/topic/greeting", text);
}
}
Run Code Online (Sandbox Code Playgroud)
两者非常相似.第一个覆盖默认构造函数,不会自动装配模板初始化.第二个不会创建新的构造函数,但会自动装配模板初始化.我的第一个问题是这两个行为是否相同?
更紧迫的是我无法从任何地方调用"问候"方法.我尝试过几种不同的方式.
这是第一个:
public class modifier {
@Autowired
private HelloController sender;
public void adder(String words) throws Exception {
sender.greet(words);
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,似乎新的HelloController从未初始化.在调试时,我发现当adder方法调用"greet"方法时,发送方为null并且我收到空指针异常.
这是我用来设置的另一条路线:
public class modifier {
public void adder(String words) throws Exception {
HelloController sender = new HelloController();
sender.greet(words);
}
Run Code Online (Sandbox Code Playgroud)
}
在上面的第二种情况下,在调试之后,还有一个空指针异常,但它不是发送者.它与sender.template一起使用.发件人的模板已初始化,但永远不会给出值或id.然后在greet中调用this.template.convertAndSend()时,会在this.template上引发空指针异常.
我混合并匹配了控制器的两个实现和我在应用程序中从一个单独的类调用greet方法的两个实现,但没有工作.
有没有人可以解释我的问题?任何帮助,提示或建议将不胜感激!
提前致谢.
正如注释中正确写的那样,有多种方法可以自动装配依赖项,它们大多是等效的,您必须根据需要选择您喜欢的方法。
根据另一个问题:在 Spring 中,控制器是监听用户请求的对象(单例),因此映射 @RequestMapping 处理对指定 url 的 HTTP 请求。
如果您需要使用 SimpMessagingTemplate 对象将消息从服务器推送到客户端,您必须知道客户端必须使用 STOMP 协议(通过 Websockets),并且必须订阅正确的主题。
事实上,使用STOMP,服务器不能任意推送消息给客户端,而只能将消息发布到主题,并且客户端必须订阅正确的主题才能接收消息。
| 归档时间: |
|
| 查看次数: |
5664 次 |
| 最近记录: |