@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 { }
本文来自博客园,作者:huiy_小溪,转载请注明原文链接:https://www.cnblogs.com/huiy/p/13378534.html