【问题标题】:Springboot @ServerEndPoint "Failed to find the root WebApplicationContext."Springboot @ServerEndPoint“找不到根 WebApplicationContext。”
【发布时间】:2015-08-09 13:49:47
【问题描述】:

我在使用带有 @ServerEndPoint 注释类的 spring 时遇到问题

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

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

弹簧配置:

@ConditionalOnWebApplication
@Configuration
public class WebSocketConfigurator {

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

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

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);
        }
    }

这是基于Spring WebSocket JSR-356 tutorial,但我收到以下错误:

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)

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

the only workaround i've found is to create a custom configurator.

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);
    }

它被创建为带有参数化构造函数的@Bean。

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

【问题讨论】:

  • 我建议 this one 而不是遵循该教程,因为它是为 Spring Boot 而不是普通的 spring 量身定制的。
  • 本教程使用 STOMP 协议,我必须坚持使用纯文本 websocket,因为我们使用自定义协议。还是我错过了什么?

标签: java spring websocket spring-boot jsr356


【解决方案1】:

SpringConfigurator 使用ContextLoader 获取弹簧上下文。 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;
    }
}

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

@ConditionalOnWebApplication
@Configuration
public class WebSocketConfigurator {

...

    @Bean
    public CustomSpringConfigurator customSpringConfigurator() {
        return new CustomSpringConfigurator(); // This is just to get context
    }
}

那么你需要正确设置配置器:

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

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

【讨论】:

  • 我不知道你在做什么,但是非常感谢,它对我有用
【解决方案2】:

使用 Spring Boot,Spring 上下文不会通过 SpringContextLoaderListener 加载,这是 SpringConfigurator.class 所要求的。

这就是需要端点和 ServerEndpointExporter bean 的原因。

要使示例正常运行,您唯一需要做的就是从 @ServerEndPoint 端点定义中删除 SpringConfigurator.class

【讨论】:

  • 感谢您的回复,但我想要的是拥有一个 ServerEndPoint 实例。使用 ServerEndpointExporter,每个传入的套接字连接都有一个新实例。
  • 端点如何在 ServerEndpointExporter 中注册以及如何使用它......我不明白 docs.spring.io/spring-framework/docs/current/javadoc-api/org/… 中的那个。你能给我举个例子吗?
【解决方案3】:

感谢 Sergi Almar 和 his answer,我已经设法使用 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);
        }
    }
}

配置文件:

@ConditionalOnWebApplication
@Configuration
public class WebSocketConfigurator implements WebSocketConfigurer {

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

    @Bean
    public SpringWebSocketHandler myHandler() {
        return new SpringWebSocketHandler();
    }
}

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

org.springframework.web.util.WebUtils : Failed to parse Origin header value [localhost:8080]

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

【讨论】:

    猜你喜欢
    • 2013-08-30
    • 2018-06-24
    • 2018-09-20
    • 2014-12-23
    • 1970-01-01
    • 2021-09-15
    • 2012-02-14
    • 2017-02-01
    • 1970-01-01
    相关资源
    最近更新 更多