问题:@ServerEndpoint类中的@Autowired bean为null
如何确保下面的WebSocketController类将注入bean,即如何让它由Spring管理?我可以连接到websocket,所以它可以工作,但是gameService在WebSocketController类实例中总是为null,所以我认为它是由tomcat以某种方式而不是Spring创建的。
我使用Spring启动。我只需要弄清楚如何将bean注入这个websocket控制器类。
WebSocketController类
@Component
@ServerEndpoint("/sock")
public class WebSocketController {
@Autowired
private GameService gameService;
private static Set<Session> clients = Collections.synchronizedSet(new HashSet<Session>());
@OnMessage
public void handleMessage(Session session, String message) throws IOException {
session.getBasicRemote().sendText(
"Reversed: " + new StringBuilder(message).reverse());
}
@OnOpen
public void onOpen(Session session) {
clients.add(session);
System.out.println("New client @"+session.getId());
if (gameService == null) System.out.println("game service null");
}
@OnClose
public void onClose(Session session) {
clients.remove(session);
System.out.println("Client disconnected @" + session.getId());
}
}
GameService接口和实现
public interface GameService {
List<Character> getCharacters();
}
@Service
public class GameServiceMockImpl implements GameService {
@Override
public List<Character> getCharacters() {
List<Character> list = new ArrayList<>();
list.add(new Character("aaa","1.png",100));
list.add(new Character("aaa","2.jpg",100));
list.add(new Character("aaa","3.jpg",100));
return list;
}
}
申请类
@SpringBootApplication
public class App {
public static void main(String args[]){
SpringApplication.run(App.class,args);
}
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
编辑:
使用Spring 4 WebSockets根本不起作用,我甚至无法通过浏览器连接。
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "/myHandler");
}
@Bean
public WebSocketHandler myHandler() {
return new MyHandler();
}
}
public class MyHandler extends TextWebSocketHandler {
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
System.out.println(message.getPayload());
}
}
答案 0 :(得分:3)
也许这篇文章可以提供帮助:
https://spring.io/blog/2013/05/23/spring-framework-4-0-m1-websocket-support
您可以使用依赖项(使用spring版本&gt; 4)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${spring.version}</version>
</dependency>
然后简单地
@ServerEndpoint(value = "/echo", configurator = SpringConfigurator.class)
public class WebSocketEndpoint {
@Inject
private BroadcastService broadcaster;
答案 1 :(得分:1)
您正在尝试集成Spring和Java WebSocket API。注释为@Component
的类被注册到spring bean,其实例由spring管理,但如果类由@ServerEndpoint
注释,则它被注册到服务器端WebSocket端点,并且每次都对应端点& #39; s WebSocket连接到服务器,其实例由JWA实现创建和管理。我们不能同时使用这两个注释。
您可以使用CDI注入(您的服务器也应该支持)
@ServerEndpoint("/sock")
public class WebSocketController {
@Inject
private GameService gameService;
或者查看this doc,Spring 4支持WebSocket