Springboot @ServerEndPoint"无法找到根WebApplicationContext."

Y.M*_*.M. 7 java spring websocket spring-boot jsr356

我在使用带有@ServerEndPoint注释类的spring时遇到了麻烦

我正在使用Springboot 1.2.3,我正试图弄清楚如何拥有一个端点的单个实例

@SpringBootApplication
@EnableJpaRepositories
@EnableWebSocket
public class ApplicationServer {
    public static void main(String[] args) {
        SpringApplication.run(ApplicationServer.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

弹簧配置:

@ConditionalOnWebApplication
@Configuration
public class WebSocketConfigurator {

    @Bean
    public ServerEndPoint serverEndpoint() {
        return new ServerEndPoint();
    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
Run Code Online (Sandbox Code Playgroud)

WebSocket端点:

@ServerEndpoint(value = "/", decoders = MessageDecoder.class, 
encoders = MessageEncoder.class, configurator = SpringConfigurator.class)
public class ServerEndPoint {

    private static final Logger LOG = LoggerFactory.getLogger(ServerEndPoint.class);

    public static final Set<CommunicationObserver> OBSERVERS = Sets.newConcurrentHashSet();

    @OnMessage
    public void onMessage(Session session, Message msg) {
        LOG.debug("Received msg {} from {}", msg, session.getId());
        for (CommunicationObserver o : OBSERVERS) {
            o.packetReceived(session, msg);
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是基于Spring WebSocket JSR-356教程,但我有以下错误:

java.lang.IllegalStateException: Failed to find the root WebApplicationContext. Was ContextLoaderListener not used?
    at org.springframework.web.socket.server.standard.SpringConfigurator.getEndpointInstance(SpringConfigurator.java:68)
    at org.apache.tomcat.websocket.pojo.PojoEndpointServer.onOpen(PojoEndpointServer.java:50)
    at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.init(WsHttpUpgradeHandler.java:138)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:687)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Run Code Online (Sandbox Code Playgroud)

我已经在嵌入模式和外部tomcat 8和jetty 9中进行了测试(在外部模式下,我删除了de Spring配置文件)但出现了同样的错误.

我发现的唯一解决方法是创建自定义配置程序.

public class SpringEndpointConfigurator extends ServerEndpointConfig.Configurator {

    private static WebApplicationContext wac;

    public SpringEndpointConfigurator() {
    }

    public SpringEndpointConfigurator(WebApplicationContext wac) {
        SpringEndpointConfigurator.wac = wac;
    }

    @Override
    public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
        T endPoint = wac.getAutowireCapableBeanFactory().getBean(endpointClass);
        return (endPoint != null) ? endPoint : wac.getAutowireCapableBeanFactory().createBean(endpointClass);
    }
Run Code Online (Sandbox Code Playgroud)

它是使用参数化构造函数创建的@Bean.

我一定错过了使用SpringConfigurator类完成它的东西,但我不知道是什么.

bhd*_*rkn 5

SpringConfigurator用于ContextLoader获取Spring上下文。Spring Boot确实设置了ServletContext,但是它从不使用ContextLoaderListener初始化ContextLoader来保存Spring上下文的静态状态。您可以尝试添加ContextLoaderListener或作为变通办法,可以编写自己的上下文持有者和配置程序。

这是一个例子:

第一个上下文持有者和配置者:

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.websocket.server.ServerEndpointConfig;

public class CustomSpringConfigurator extends ServerEndpointConfig.Configurator implements ApplicationContextAware {

    /**
     * Spring application context.
     */
    private static volatile BeanFactory context;

    @Override
    public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
        return context.getBean(clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        CustomSpringConfigurator.context = applicationContext;
    }
}
Run Code Online (Sandbox Code Playgroud)

为了获得上下文,我们需要将其配置为Bean:

@ConditionalOnWebApplication
@Configuration
public class WebSocketConfigurator {

...

    @Bean
    public CustomSpringConfigurator customSpringConfigurator() {
        return new CustomSpringConfigurator(); // This is just to get context
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您需要正确设置配置器:

@ServerEndpoint(value = "/", decoders = MessageDecoder.class, 
encoders = MessageEncoder.class, configurator = CustomSpringConfigurator.class)
public class ServerEndPoint {
...
}
Run Code Online (Sandbox Code Playgroud)

附带说明,是的,如果删除SpringConfigurator您的应用程序将启动,并且可以处理请求。但是您不能自动连接其他bean。


Y.M*_*.M. 1

感谢 Sergi Almar 和他的回答,我成功地使用 Spring 实现而不是 javax.websocket 实现:

public class SpringWebSocketHandler extends TextWebSocketHandler {

    private final Set<CommunicationObserver> observers = Sets.newConcurrentHashSet();

    @Autowired
    private MessageContext mc;

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        Message msg = mc.parse(message.getPayload());

        for (CommunicationObserver o : observers) {
            o.packetReceived(session, msg);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

配置文件:

@ConditionalOnWebApplication
@Configuration
public class WebSocketConfigurator implements WebSocketConfigurer {

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

    @Bean
    public SpringWebSocketHandler myHandler() {
        return new SpringWebSocketHandler();
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,setAllowedOrigins(“*”)对我来说是强制性的,因为在使用java客户端时,我遇到了以下错误:

org.springframework.web.util.WebUtils : Failed to parse Origin header value [localhost:8080]
Run Code Online (Sandbox Code Playgroud)

另请注意,MessageContext 用于解析/格式化字符串,而不是 MessageEncoder/Decoder 类(它们继承自 MessageContext)。