SpringBoot + WebSocket 无法注入其它Bean解决方案

SpringBoot + WebSocket 无法注入其它Bean解决方案

  •  11个月前
  •  1063
  •  SpringBoot WebSocket 

SpringBoot整合WebSocket,当我尝试注入RedisTemplate的时候出现了无法注入的情况。

原关键代码如下

@ServerEndpoint(value = "/ws")

@Autowired
private StringRedisTemplate stringRedisTemplate;

原因

SpringConfigurator uses ContextLoader to obtain spring context. Spring Boot does set up the ServletContext but it never uses ContextLoaderListener which initializes ContextLoader to hold static state of spring context. 

解决方案

1、添加配置

import javax.websocket.server.ServerEndpointConfig;

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

@Component
public class EndpointConfig extends ServerEndpointConfig.Configurator implements ApplicationContextAware {

    private static volatile BeanFactory context;

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

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

}

2、把 @ServerEndpoint(value = "/ws") 修改为 @ServerEndpoint(value = "/ws", configurator = EndpointConfig.class)

这样就可以正常注入Bean了

附上StackOverflow上的问题:https://stackoverflow.com/questions/30483094/springboot-serverendpoint-failed-to-find-the-root-webapplicationcontext

扫一扫分享到微信

已有 条评论
写评论