如何将 属性 注入 WebSocketHandler?

How do I inject a property into a WebSocketHandler?

我在为 class 实现 WebSocketHandler 进行简单 属性 注入时遇到问题,该 WebSocketHandler 通过 PerConnectionWebSocketHandler 使用。

这个例子在没有 @Value 注释字段的情况下工作正常,但是当我添加 @Value 注释字段时,当网络套接字连接时它失败: java.lang.IllegalStateException: WebSocketHandler not found for StandardWebSocketSession

如何在 MyHandler class 中注入 @Value 字段?

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 class 中的 属性 名称存在拼写错误。

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

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

injectionexample=injected