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