I'm trying to send a message with a Rabbitmq in WebSocketHandler, right after the user's connection establishes. The problem is, that the Rabbitmq producer bean is null. Calling a producer from the Controller works perfectly fine, but when i try to call it from the WebSocketHandler bean, if fails with NULL pointer exception:
WebSocket configuration:
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyWebSocketHandler(), "/connect");
}
}
WebSocket handler bean, where the NULL pointer exceptions heppens:
@Component
public class MyWebSocketHandler extends TextWebSocketHandler {
private static final Logger LOG = LoggerFactory.getLogger(WebSocketConfig.class);
@Autowired
QueueProducer producer; //NULL
List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
List<String> lol = session.getHandshakeHeaders().get("User-Agent");
//Calling the rabbitmq producer
producer.produce("Hi Mark");//NULL
}
Rabbitmq config:
@Configuration
public class RabbitConfiguration {
@Value("${fanout.exchange}")
private String fanoutExchange;
@Value("${queue.name}")
private String queueName;
@Bean
Queue queue() {
return new Queue(queueName, true);
}
@Bean
FanoutExchange exchange() {
return new FanoutExchange(fanoutExchange);
}
@Bean
Binding binding(Queue queue, FanoutExchange exchange) {
return BindingBuilder.bind(queue).to(exchange);
}
}
Rabbitmq producer code:
@Component
public class QueueProducer {
protected Logger logger = LoggerFactory.getLogger(getClass());
@Value("${fanout.exchange}")
private String fanoutExchange;
private final RabbitTemplate rabbitTemplate;
@Autowired
public QueueProducer(RabbitTemplate rabbitTemplate) {
super();
this.rabbitTemplate = rabbitTemplate;
}
public void produce(String message) throws Exception {
logger.info("Storing notification...");
rabbitTemplate.setExchange(fanoutExchange);
rabbitTemplate.convertAndSend(message);
logger.info("Notification stored in queue sucessfully");
}
}
Stack Trace:
java.lang.NullPointerException: null
at com.ta9.common.Config.MyWebSocketHandler.afterConnectionEstablished(MyWebSocketHandler.java:43) ~[classes/:na]
at org.springframework.web.socket.handler.WebSocketHandlerDecorator.afterConnectionEstablished(WebSocketHandlerDecorator.java:70) ~[spring-websocket-5.3.8.jar:5.3.8]
at org.springframework.web.socket.handler.LoggingWebSocketHandlerDecorator.afterConnectionEstablished(LoggingWebSocketHandlerDecorator.java:48) ~[spring-websocket-5.3.8.jar:5.3.8]
at org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator.afterConnectionEstablished(ExceptionWebSocketHandlerDecorator.java:48) ~[spring-websocket-5.3.8.jar:5.3.8]
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.onOpen(StandardWebSocketHandlerAdapter.java:104) ~[spring-websocket-5.3.8.jar:5.3.8]
at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.init(WsHttpUpgradeHandler.java:135) ~[tomcat-embed-websocket-9.0.48.jar:9.0.48]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:940) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
Thank you in advance.
That's expected behavior. Let's see to your code one more time:
registry.addHandler(new MyWebSocketHandler(), "/connect");
You see you do new
manually. You don't rely on dependency injection container over here. Your MyWebSocketHandler
is not a bean in this case. Since it is marked as a @Component
I suppose it is scanned properly and made it available as a bean into an application context. So, probably you can do like this to fix your problem:
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Autowired
MyWebSocketHandler myWebSocketHandler;
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(this.myWebSocketHandler, "/connect");
}
}