记录spring springboot websocket 不能注入( @Autowired ) 解决问题的过程

在WebSocket使用@service注解的service类时,启动没有问题,在发送聊天信息的时候,出现异常:java.lang.NullPointException,过程中找到很多的解决方案,但是这些方法都没有解决,会出现其他的一些错误。
最终得以解决,记录此贴以供后面查阅。

第一种方式:在@ServerEndpoint 注解后面添加 configurator = SpringConfigurator.class

如下

@ServerEndpoint(value = "/websocket/{user}", configurator = SpringConfigurator.class)
@Controller

这种方式会出现以下错误,从字面意思上来看是ContextLoaderListener没有运行。

java.lang.IllegalStateException: Failed to find the root WebApplicationContext. Was ContextLoaderListener not used?

ContextLoaderListener 是spring MVC web.xml的配置文件,跟Spring boot 关系好像不大,就没有深入,换一种方式。

第二种方式:在websock的配置类中配置websock类

如下:

@Configuration
public class EndpointConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        ServerEndpointExporter serverEndpointExporter = new ServerEndpointExporter();
        serverEndpointExporter.setAnnotatedEndpointClasses(WebsocketController.class);
        return serverEndpointExporter;
    }
}

WebsocketController 是websocket 实现类,依然没有解决。

第三种方式:重写ApplicationContextAware 类

如下:

@Component
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringUtil .applicationContext == null) {
            SpringUtil .applicationContext = applicationContext;
        }
    }
    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    public static Object getBean(String beanName){
        return applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<T> clazz){
        return (T)applicationContext.getBean(clazz);
    }

}

然后,通过getBean获取Service方法

private static WeChatService weChatService = SpringUtil .getBean(WeChatService.class);

看上去这个方法很可行啊,启动,报错 …

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'websocketController' defined in file

bean创建失败,正准备攻克这个问题时,无意中发现了另一个解决方法。

第四种方式:初始化Service 类,再通过@Autowired 进行赋值

如下:

	private static WeChatService weChatService ;

	@Autowired
	public void setWeChatService(WeChatService weChatService){
		this.weChatService = weChatService;
	}

至此问题解决。

但是第三种方式到底可不可行,有待大佬留言!!!

end!

发布了24 篇原创文章 · 获赞 11 · 访问量 5422

猜你喜欢

转载自blog.csdn.net/weixin_44037376/article/details/97644830