Send Message to all clients via SimpMessagingTemplate in ServletContextListener

This solution worked great.

For anybody who wants a quick solution - strip out all the "Notifier" stuff and just inject MessagingApplicationListener into your class. Then call 'notify' with a String to send a message. Obviously, as @battmanz says you'll want some way to push events to the listener, but this class does the basics of what you need.


The solution was to use Spring's ApplicationListener class instead of a ServletContextListener, and to specifically listen for the ContextRefreshedEvent.

This is my working example:

@Component
public class MessagingApplicationListener implements ApplicationListener<ContextRefreshedEvent>, Notifiable {
    private final NotifierFactor notifierFactory;
    private final MessageSendingOperations<String> messagingTemplate;
    private Notifier notifier;

    @Autowired
    public MessagingApplicationListener(NotifierFactor notifierFactory, MessageSendingOperations<String> messagingTemplate) {
        this.notifierFactory = notifierFactory;
        this.messagingTemplate = messagingTemplate;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (notifier == null) {
            notifier = notifierFactory.create(this);
            notifier.start();
        }
    }

    public void notify(NotifyEvent event) {
        messagingTemplate.convertAndSend("/topic/greetings", new Greeting("Hello, " + event.subject + "!"));
    }

    @PreDestroy
    private void stopNotifier() {
        if (notifier != null) {
            notifier.stop();
        }
    }
}