对于最新稳定版本,请使用 Spring Framework 7.0.6spring-doc.cadn.net.cn

发送消息

如果你希望从应用程序的任意位置向已连接的客户端发送消息,该怎么办?任何应用程序组件都可以向 brokerChannel 发送消息。 最简单的方法是注入一个 SimpMessagingTemplate 并使用它来发送消息。通常,你会按类型进行注入,如下例所示:spring-doc.cadn.net.cn

@Controller
public class GreetingController {

	private SimpMessagingTemplate template;

	@Autowired
	public GreetingController(SimpMessagingTemplate template) {
		this.template = template;
	}

	@RequestMapping(path="/greetings", method=POST)
	public void greet(String greeting) {
		String text = "[" + getTimestamp() + "]:" + greeting;
		this.template.convertAndSend("/topic/greetings", text);
	}

}

然而,如果存在另一个相同类型的 bean,你也可以通过其名称(brokerMessagingTemplate)来限定它。spring-doc.cadn.net.cn