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:

  1. The client sends JSON to /app/score.update.
  2. The /app prefix is stripped, and the method matching /score.update is found.
  3. The payload is converted to Score through Jackson.
  4. 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.