Using Java API for WebSocket (JSR-356) with Spring Boot

半世苍凉 提交于 2019-12-05 03:14:29

ServerEndpointExporter makes some assumptions about the lifecycle of an application context that don't hold true when you're using Spring Boot. Specifically, it's assuming that when setApplicationContext is called, calling getServletContext on that ApplicationContext will return a non-null value.

You can work around the problem by replacing:

@Bean
public ServerEndpointExporter endpointExporter() {
    return new ServerEndpointExporter();
} 

With:

@Bean
public ServletContextAware endpointExporterInitializer(final ApplicationContext applicationContext) {
    return new ServletContextAware() {

        @Override
        public void setServletContext(ServletContext servletContext) {
            ServerEndpointExporter serverEndpointExporter = new ServerEndpointExporter();
            serverEndpointExporter.setApplicationContext(applicationContext);
            try {
                serverEndpointExporter.afterPropertiesSet();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }               
        }           
    };
}

This defers the processing until the servlet context is available.

Update: You may like to watch SPR-12109. Once it's fixed the workaround described above should no longer be necessary.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!