WebSockets JSR 356 Spring integration @ServerEndpoint

一世执手 提交于 2019-12-23 22:19:07

问题


Problem: @Autowired beans in @ServerEndpoint class are null

How can I make sure that this WebSocketController class below will be injected with beans, that is how can I make it managed by Spring? I can connect to the websocket so it works but gameService is always null inside the WebSocketController class instance, so I think that it is created by tomcat somehow and not Spring.

I'm using Spring boot. I just need to figure out how to inject beans into this websocket controller class.

WebSocketController class

@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 interface and implementation

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;
    }
}

Application class

@SpringBootApplication
public class App  {

    public static void main(String args[]){
        SpringApplication.run(App.class,args);
    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

EDIT:

Using Spring 4 WebSockets doesn't work at all, I can't even connect via a browser.

@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());
    }

}

回答1:


You are trying to integrate Spring and Java WebSocket API. A class annotated by @Component is registered to a spring bean and its instance is managed by spring but if a class is annotated by @ServerEndpoint it is registered to a server-side WebSocket endpoint and every time the corresponding endpoint's WebSocket is connected to the server, its instance is created and managed by JWA implementation. We you can't use both annotations together.

Either you can use CDI injection(your server should also support)

@ServerEndpoint("/sock")
public class WebSocketController {

    @Inject
    private GameService gameService;

Or have a look on this doc, Spring 4 has support for WebSocket




回答2:


Maybe this article can help:

https://spring.io/blog/2013/05/23/spring-framework-4-0-m1-websocket-support

You can use dependency (with spring version > 4)

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-websocket</artifactId>
    <version>${spring.version}</version>
</dependency>

And then simply

@ServerEndpoint(value = "/echo", configurator = SpringConfigurator.class)
public class WebSocketEndpoint {

    @Inject
    private BroadcastService broadcaster;


来源:https://stackoverflow.com/questions/34246382/websockets-jsr-356-spring-integration-serverendpoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!