websocket 中使用Service层的方法
作者:互联网
课设做了个使用websocket在线聊天的小demo,在websocket调用service层时,报空指针异常,底层程序员就只会百度了~
记下这个解决办法吧。
首先创建一个类
import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; @Component @Lazy(false) public class ApplicationContextRegister implements ApplicationContextAware { private static ApplicationContext APPLICATION_CONTEXT; /** * 设置spring上下文 * * @param applicationContext spring上下文 * @throws BeansException */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { APPLICATION_CONTEXT = applicationContext; } public static ApplicationContext getApplicationContext() { return APPLICATION_CONTEXT; } }
然后在要调用service层的地方添加如下内容:
ApplicationContext act = ApplicationContextRegister.getApplicationContext(); storageService=act.getBean(StorageService.class); ((StorageService) storageService).save(storage);
嗯,就差不多了。
参考:https://blog.csdn.net/u010919083/article/details/79388720
标签:ApplicationContext,websocket,Service,BeansException,springframework,org,import,方 来源: https://www.cnblogs.com/lyuyi/p/11100130.html