解决springboot+webSocket出现404错误

在这里插入图片描述
这是因为websocket创建的bean是由自己来管理的,需要将其创建的bean交给spring管理

创建websocketconfig
在这里插入图片描述

package com.meikesen.net;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @Author dfj
 * @Date 2020/10/13 10:21
 */
@Configuration
public class WebSocketConfig {
    /**
     * ServerEndpointExporter 作用
     *
     * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Bean
    public MySpringConfigurator mySpringConfigurator() {
        return new MySpringConfigurator();
    }


}
只是这样还不可以,spring并没有直接的获取到ServerEndpoint这个bean,还需要配置一个类来实现spring的动态代理
package com.meikesen.net;

/**
 * 以websocketConfig.java注册的bean是由自己管理的,需要使用配置托管给spring管理
 *
 * @Author dfj
 * @Date 2020/10/13 10:28
 */

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 MySpringConfigurator extends ServerEndpointConfig.Configurator implements ApplicationContextAware {

    private static volatile BeanFactory context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        MySpringConfigurator.context = applicationContext;
    }

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

如此一来,spring就可以获取到websocket所创建的bean了

PS:websocket类上需要加上@comment注解~~~


版权声明:本文为weixin_45213446原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。