开发一个微信小程序后台,创建websocket 长链接,须要后台开启定时任务,java
定时任务定时查库,相应前台web
可是具体执行过程当中一直在报空指针错误,最后定位到service 为空,没法调用其相关的方法致使的spring
因而我尝试不用@Autowired 注入实例,本身new ,可是仍是失败了,报空指针小程序
这是spring的一个Bug ,须要手动去配置一个类,主动获取实例,在定时任务中(继承TimerTask类),@Autowired 是失效的,没法注入微信小程序
解决方案以下:微信
1.首先添加一个工具类,就是applicationwebsocket
应注意,一样须要注入添加 @Compent注解app
package com.cskaoyan.carparking.utils; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; /** * @Auther: YangTao * @Date: 2019/2/21 0021 * 配置类,解决定时任务没法注入的问题 */ @Component public class ApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; public static ApplicationContext getApplicationContext() { return applicationContext; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ApplicationContextUtil.applicationContext = applicationContext; } public static Object getBean(String beanName) { return applicationContext.getBean(beanName); }
2.在咱们的servcie的实现类注解添加名字,以便咱们获取socket
3.咱们在须要的定时任务类中获取service实例就能够使用了ide
StopService stopService = (StopService) ApplicationContextUtil.getBean("myService");