如何在Web Socket处理程序中注入依赖项:
public class WebsocketHandler extends AbstractWebSocketHandler {
@Autowired
GreetingMap greetingMap;
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
// NullPointerException here
String greeting = greetingMap.getSampleGreetings().get("hello") + " " + message.getPayload();
session.sendMessage(new TextMessage(greeting));
}
}
上面的代码抛出NullPointerException
这里可能缺少什么?
答案 0 :(得分:2)
尝试通过构造函数而不是@Autowired使用依赖项注入:
private GreetingMap greetingMap;
public WebsocketHandler(GreetingMap greetingMap){
this.greetingMap = greetingMap
}