@ServerEndpoint:无法主入bean

Posted huiy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了@ServerEndpoint:无法主入bean相关的知识,希望对你有一定的参考价值。

解决办法:

import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@ConditionalOnWebApplication
@Configuration
public class WebSocketConfigurator {

  @Bean
  public CustomSpringConfigurator customSpringConfigurator() {
    return new CustomSpringConfigurator(); // This is just to get context
  }
}
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;
    }
}
@Component
@ServerEndpoint(value = "/websocket/car/",configurator = CustomSpringConfigurator.class)
public class WebSocketCar {



}

以上是关于@ServerEndpoint:无法主入bean的主要内容,如果未能解决你的问题,请参考以下文章

@ServerEndpoint(“/websocket”)404

SpringBoot使用@ServerEndpoint无法依赖注入问题解决 SpringBoot webSocket配置

@ServerEndpoint 和 @Autowired

@ServerEndpoint 和 Spring MVC 注入

从 Web Socket @ServerEndpoint 中的 HttpServletRequest 访问 HttpSession

ServerEndpoint 和 web.xml