Video in progress
What do the @MessageMapping and @SendTo annotations do in Spring?
@MessageMapping routes a STOMP message from the client to a method by destination; it's the messaging equivalent of @RequestMapping. @SendTo sends the value the method returns to all subscribers of the given topic.
📖 Answer
@Controller
public class ScoreController {
// the client SENDs to "/app/score.update"
@MessageMapping("/score.update")
@SendTo("/topic/scores")
public Score update(Score score, Principal user) {
return scoreService.save(score, user.getName());
}
}
Here is what happens:
- The client sends JSON to
/app/score.update. - The
/appprefix is stripped, and the method matching/score.updateis found. - The payload is converted to
Scorethrough Jackson. - The returned object goes to every client subscribed to
/topic/scores.
If you don't add @SendTo, Spring by default sends the reply to /topic plus the incoming destination (that is, /topic/score.update). People who don't know this end up hunting for "where did my reply go?".
The method can also take Principal, @Header, @DestinationVariable and SimpMessageHeaderAccessor as parameters.
Sign up to mark studied questions and save your progress.