如何将属性注入WebSocketHandler?

时间:2016-07-29 21:33:45

标签: java dependency-injection spring-boot spring-java-config

对于通过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

1 个答案:

答案 0 :(得分:1)

WebSocketHandler类中的属性名称中存在拼写错误。

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

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

injectionexample=injected