Path variables in Spring WebSockets @SendTo mapping

Even though @MessageMapping supports placeholders, they are not exposed / resolved in @SendTo destinations. Currently, there’s no way to define dynamic destinations with the @SendTo annotation (see issue SPR-12170). You could use the SimpMessagingTemplate for the time being (that’s how it works internally anyway). Here’s how you would do it:

@MessageMapping("/fleet/{fleetId}/driver/{driverId}")
public void simple(@DestinationVariable String fleetId, @DestinationVariable String driverId) {
    simpMessagingTemplate.convertAndSend("/topic/fleet/" + fleetId, new Simple(fleetId, driverId));
}

In your code, the destination ‘/topic/fleet/{fleetId}‘ is treated as a literal, that’s the reason why subscribing to it works, just because you are sending to the exact same destination.

If you just want to send some initial user specific data, you could return it directly in the subscription:

@SubscribeMapping("/fleet/{fleetId}/driver/{driverId}")
public Simple simple(@DestinationVariable String fleetId, @DestinationVariable String driverId) {
    return new Simple(fleetId, driverId);
}

Update:
In Spring 4.2, destination variable placeholders are supported it’s now possible to do something like:

@MessageMapping("/fleet/{fleetId}/driver/{driverId}")
@SendTo("/topic/fleet/{fleetId}")
public Simple simple(@DestinationVariable String fleetId, @DestinationVariable String driverId) {
    return new Simple(fleetId, driverId);
}

Leave a Comment