在Quartz的定时方法里引用@Autowired注入Bean,会报空指针错误

解决办法:

第一种方法:(推荐,简单,亲测可行)

使用@Resource(name="指定要注入的Bean"),代替@Autowired即可,指定了要注入的Bean名字,就能找到该Bean,就不会空指针了。

@Resource(name = "deviceStateProducerService")
private DeviceStateProducerService deviceStateProducerService;

示例代码:

看下面红色字体部分

代码

@Service("microDeviceStateService")
public class MicroDeviceStateServiceImpl implements MicroDeviceStateService { @Resource(name = "deviceStateProducerService")
private DeviceStateProducerService deviceStateProducerService; @Scheduled(cron="0/10 * * * * * ?")
@Lazy(false)
public void pingDeviceState() {
boolean isSuccess = PingUtils.ping("127.0.0.1", , );
MicroDeviceState microDeviceState = new MicroDeviceState();
if(!isSuccess) {
logger.debug("连接设备状态失败!");
microDeviceState.setDeviceState("");
}else {
microDeviceState.setDeviceState("");
} microDeviceState.setDeviceFlag("");
microDeviceState.setIp("127.0.0.1");
DeviceStateBase deviceStateBase = new DeviceStateBase();
BeanUtils.copyProperties(microDeviceState, deviceStateBase);
deviceStateProducerService.deviceStateSender(deviceStateBase);
} }

有的定时器不生效,在类上加注解@EnableScheduling(spring自带的定时任务功能)

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd"
default-lazy-init="true"> <task:scheduler id="scheduler" pool-size="" />
<task:executor id="executor" keep-alive="" pool-size="100-200"
queue-capacity="" rejection-policy="CALLER_RUNS" />
<task:annotation-driven executor="executor" scheduler="scheduler" />
<!-- 注解配置定时器 -->
<context:annotation-config />
<!-- spring扫描注解的配置(要扫描的包,即定时器所在包) -->
<context:component-scan base-package="com.zit.adapter.camera.CameraListener" /> </beans>

第二种方法:(也可行,不推荐)

使用Spring原生获取Bean的方法 取代 @Autowired注入,同时,不要与定时方法在同一个类

示例代码:

注解方式写了一个定时方法,方法里需要引用Dao层,插入数据库,

直接@Autowired会报空指针异常,做出如下红色字体改动

public class FTPUtil{

//    @Autowired
// MicroCameraPassRecordDao microCameraPassRecordDao; private static MicroCameraPassRecordDao microCameraPassRecordDao = null; 使用Spring获取注入bean
static {
microCameraPassRecordDao =
(MicroCameraPassRecordDao) SpringContextUtils.getApplicationContext().getBean("microCameraPassRecordDao");
} /**
* 定时从FTP下载图片到本地,在这个方法里调用别的Dao层的方法
*/
@Scheduled(cron="0/20 * * * * * ?")
@Lazy(false)
public synchronized void service() {
FTPUtil ftpUtil = new FTPUtil();
boolean isConnect = ftpUtil.connectServer();
//从FTP下载到工程file下
boolean flag = ftpUtil.download(getFtpPath()); //引用注入Bean,插入数据库
MicroCameraPassRecord cameraRecord = new MicroCameraPassRecord();
cameraRecord.setCameraId(deviceID);
cameraRecord.setAddTime(System.currentTimeMillis());
microCameraPassRecordDao.insert(cameraRecord); } }

getBean(引用类名,开头字母小写)

 SpringContextUtils

Spring获取Bean的工具类:

package com.zit.util;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service; @SuppressWarnings({ "rawtypes", "unchecked" })
@Service("springContextUtils")
public class SpringContextUtils implements ApplicationContextAware { private static ApplicationContext applicationContext; public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
applicationContext = arg0;
} /**
* 获取applicationContext对象
* @return
*/
public static ApplicationContext getApplicationContext(){
return applicationContext;
} /**
* 根据bean的id来查找对象
* @param id
* @return
*/
public static Object getBeanById(String id){
return applicationContext.getBean(id);
} /**
* 根据bean的class来查找对象
* @param c
* @return
*/
public static Object getBeanByClass(Class c){
return applicationContext.getBean(c);
} /**
* 根据bean的class来查找所有的对象(包括子类)
* @param c
* @return
*/
public static Map getBeansByClass(Class c){
return applicationContext.getBeansOfType(c);
} }

Quartz定时器+Spring + @Autowired注入 空指针异常的更多相关文章

  1. @Autowired 警告 Field injection is not recommended Spring @Autowired注入

    问题: 一. 在IDEA升级2017版后,发现以前使用的 @Autowired 出现了个警告 Field injection is not recommended. @Autowired的三种使用方式 ...

  2. Spring @Autowired 注入为 null

    原因 配置缺失,比如为开启注解扫描驱动.注入组件为注册: 使用 new 关键字创建的对象不受spring容器管理,无法注入: 注入静态变量, 静态变量/类变量不是对象的属性,而是一个类的属性,spri ...

  3. spring @Autowired注入map

    注入map,平常一般不会这么做,今天看一段老代码时发现有这么个用法.补习一下. @Autowired 标注作用于 Map 类型时,如果 Map 的 key 为 String 类型,则 Spring 会 ...

  4. Spring Autowired 注入失败总是Null

    报错:NullPointerException 分析:错误原因是注入失败? <context:annotation-config/> <context:component-scan ...

  5. spring@Autowired注入为null的问题,2017年9月14日21点41分记录

    这个小问题纠结了三个小时..发出来留个纪念 这是启动项目的时候 这是请求控制器的时候   图1注入的时候是null,图2请求控制器的时候是有的,这是因为图1debug的地方是构造器..autowire ...

  6. spring @Autowired注入对象,在构造方法中为null问题

    出现问题的代码如下: @Service public class BaseHttpServiceImpl implements BaseHttpClient { private final stati ...

  7. spring @Autowired注入的原理

    只知道如何用Autowired注解,知道可以替代set,get方法,很方便,却一直不知道,为什么可以代替 今天探索一下原因,所谓知其然还要知其所以然,才能理解的更好,记忆的更牢,才能转化为自己的知识. ...

  8. java Quartz定时器任务与Spring task定时的几种实现,

    java Quartz定时器任务与Spring task定时的几种实现 基于java 的定时任务实现, Quartz 时间详细配置    请查阅   http://www.cnblogs.com/si ...

  9. Spring quartz Job不能依赖注入,Spring整合quartz Job任务不能注入

    Spring quartz Job不能依赖注入,Spring整合quartz Job任务不能注入 Spring4整合quartz2.2.3中Job任务使用@Autowired不能注入 >> ...

随机推荐

  1. VC++运行库 集32位/64位整合版

    运行程序时,win7/win10(x86和x64)常会遇到缺少什么缺少msvc***.dll问题 安装下面链接提供的程序,安装后,便可解决. [2016-10-10]Microsoft Visual ...

  2. 灵雀云率先成为 Linux 基金会/CNCF官方认证培训合作伙伴

    近日,灵雀云Alauda成为Linux基金会/CNCF授权培训伙伴项目( Linux Foundation Authorized Training Partner Program,以下简称ATP)在国 ...

  3. 基于Jenkins实现持续集成【持续更新中】

    持续集成 1.什么是持续集成:Continuous integration (CI)持续集成是一种软件开发实践,即团队开发成员经常集成他们的工作,通常每个成员每天至少集成一次,也就意味着每天可能会发生 ...

  4. https://scrapingclub.com/exercise/detail_sign/

    def parse(self, response): # pattern1 = re.compile('token=(.*?);') # token = pattern1.findall(respon ...

  5. 常用git命令总结 初始化git库操作 git 子模块

    查看 git status 查看状态 Gitk 界面各个版本查看 添加 Git add filename 添加指定文件 Git add . 操作未暂存的文件 Git add -A 操作所有文件 包括删 ...

  6. js 图片无缝滚动

    html部分 <div id="roll"> <a href="javascript:void(0)" class="prev&qu ...

  7. Qt做发布版,解决声音和图片、中文字体乱码问题(需要在main里写上QApplication::addLibraryPath("./plugins")才能加载图片,有图片,很清楚)

    前些天做Qt发布版,发现居然不显示图片,后来才发现原来还有图片的库没加!找找吧,去qt的安装包,我装在了F盘,在F盘F:/QT/qt/plugins,找到了plugins,这里面有个 imagefor ...

  8. 树莓派3B安装LEDE

    本来想安装openwrt的,但是op官方没有支持pi3,甚至op都不怎么发新版了,仅LEDE分支有缓慢的更新..离题了,之前给pi3装过LEDE,体验不是很好.今天到openwrt官网看了下,发现之前 ...

  9. rangeOfString 和 containsString 兼容iOS7处理

    //查找字符串是否包含"心" NSString *str = @"每天都有好心情"; if ([str containsString:@"心" ...

  10. shell批量修改mysql用户密码

    需求 现在有这么一个需求, 需要大批量修改用户的密码, 需要注意的规则是: 必须添加的字符: *$#sjdKw% 用户名的第一位+*$#sjdKw%+用户名的最后一位,比如用户名chenglee,密码 ...