问题:@ServerEndpoint类中的@Autowired bean为空
我如何确保下面的WebSocketController类将注入bean,也就是说,我如何让它由Spring管理?我可以连接到websocket,这样它就可以工作了,但在WebSocketController类实例中,gameService总是为null,所以我认为它是由tomcat创建的,而不是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());
}
}
游戏服务接口和实现
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();
}
}
编辑:
使用Spring4WebSockets根本不起作用,我甚至无法通过浏览器进行连接。
@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());
}
}
您正在尝试集成Spring和Java WebSocket API。由@Component
注释的类被注册到springbean,其实例由spring管理,但如果类由@ServerEndpoint
注释,则它被注册到服务器端WebSocket端点,并且每次相应端点的WebSocket连接到服务器时,其实例都由JWA实现创建和管理。我们不能同时使用这两个注释。
您可以使用CDI注入(您的服务器也应该支持)
@ServerEndpoint("/sock")
public class WebSocketController {
@Inject
private GameService gameService;
或者看看这个文档,Spring 4支持WebSocket
也许这篇文章可以帮助:
https://spring.io/blog/2013/05/23/spring-framework-4-0-m1-websocket-support
您可以使用依赖项(春季版本>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;