对于通过WebSocketHandler使用的实现PerConnectionWebSocketHandler的类的简单属性注入,我遇到了问题。

此示例在没有@Value带注释的字段的情况下可以正常工作,但是当我添加@Value带注释的字段时,当Web套接字连接时,它会失败:
java.lang.IllegalStateException: WebSocketHandler not found for StandardWebSocketSession

如何获得在@Value类中注入的MyHandler字段?

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

最佳答案

WebSocketHandler类的属性名称中有一个错字。

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


与在application.properties文件中定义的方式相比,请注意额外的e

injectionexample=injected

10-07 22:27