Search code examples
javaspringspring-websocketspring-messaging

NullPointerException on SimpMessagingTemplate in Spring


I am building an application that will send messages using STOMP over websockets. I want to send messages without a request being made by the client. According to the documentation, I can do this by using convertAndSend.

However when I try and do this, I get a null pointer exception. Please see code below:

public class ParseJSON {

    @Autowired
    private SimpMessagingTemplate template;

    public void getDetails(String json) {

       try {
            Tweet status = sendDetails(TwitterObjectFactory.createStatus(json));
            sentToWebApp(status);

        } catch (TwitterException e) {
            e.printStackTrace();
        }

    }

    @Scheduled(fixedDelay = 50)
    private void sentToWebApp(Tweet status) {
        System.out.println(status);
        this.template.convertAndSend("/tweet/update", status);
    }
}

Stack Trace:

java.lang.NullPointerException: null
    at org.myproject.worker.ParseJSON.sentToWebApp(ParseJSON.java:62)
    at org.myproject.worker.ParseJSON.getDetails(ParseJSON.java:51)
    at org.myproject.worker.TwitterClient.run(TwitterClient.java:50)
    at org.myproject.Controllers.TweetController.greeting(TweetController.java:37)

Can anybody pour any light onto my situation so I'm able to send a message via websocket without encountering an exception.

Thanks in advance.


Solution

  • Your template variable is not properly autowired thats why its giving nullpointerException .

    you can check spring configuration to autowire correctly