Search code examples
javadependency-injectionspring-bootspring-java-config

How do I inject a property into a WebSocketHandler?


I am having problems with a simple property injection for a class implementing WebSocketHandler that is used through PerConnectionWebSocketHandler.

This example works fine without the @Value annotated field, but when I add the @Value annotated field, it fails when a web socket connects with: java.lang.IllegalStateException: WebSocketHandler not found for StandardWebSocketSession.

How do I get a @Value field injected in the MyHandler class?

App.java

@SpringBootApplication
@RestController
@EnableWebSocket
public class App implements WebSocketConfigurer {

    @Autowired
    private BeanFactory beanFactory;

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

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myHandler(), "/test").setAllowedOrigins("*");
    }

    @Bean
    public WebSocketHandler myHandler() {
        PerConnectionWebSocketHandler perConnectionWebSocketHandler = new PerConnectionWebSocketHandler(MyHandler.class);
        perConnectionWebSocketHandler.setBeanFactory(beanFactory);
        return perConnectionWebSocketHandler;
    }
}

MyHandler.java

@Component
public class MyHandler implements WebSocketHandler{

    /* This causes exception
    @Value("${injectioneexample}")
    private String injectionExample;
    */

    @Override
    public void handleMessage(WebSocketSession session,
            WebSocketMessage<?> encodedMessage) throws Exception {
        if (encodedMessage instanceof org.springframework.web.socket.TextMessage) {
            org.springframework.web.socket.TextMessage castedTextMessage = (org.springframework.web.socket.TextMessage) encodedMessage;
            String message = castedTextMessage.getPayload();
            session.sendMessage(new org.springframework.web.socket.TextMessage(message));
            System.out.println(message);
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession arg0, CloseStatus arg1)
            throws Exception {
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession arg0)
            throws Exception {
        //System.out.println("connected " + injectionExample);
    }

    @Override
    public void handleTransportError(WebSocketSession arg0, Throwable arg1)
            throws Exception {
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}

application.properties

injectionexample=injected

Solution

  • There is a typo in the property name in your WebSocketHandler class.

    @Value("${injectioneexample}")
    private String injectionExample;
    

    Notice the extra e compared to how you've defined it in your application.properties file.

    injectionexample=injected