背景:
在quartz job 里调用spring 容器管理的bean,出现空指针异常,即没有注入成功,在网上搜了很多类似的问题,最终发现都是copy改,经过各种折腾算是解决了问题。
解决方法有两种:
第一种方式:不去继承QuartzJobBean,只是一个独立的job bean,通过配置MethodInvokingJobDetailFactoryBean来实现;
第二种方式:继承QuartzJobBean,但是要重写SchedulerFactoryBean的jobFactory。
首先说明下版本:
<spring.version>4.0.2.RELEASE</spring.version>
<quartz.version>2.2.2</quartz.version>
代码结构如下:
说明:
MyJobAlone为不用继承方式实现的job bean
MyJobExtend为使用继承方式实现的job bean
MyQuartzJobFactory为重写的jobFactory,用于实现在使用继承方式时注入spring管理的bean
SayServiceImpl为spring 管理的bean
-SayService.java
package top.auok.quartz.bean;
public interface SayService {
void sayHello();
}
-SayServiceImpl.java
package top.auok.quartz.bean;
import org.springframework.stereotype.Service;
@Service("sayService")
public class SayServiceImpl implements SayService {
@Override
public void sayHello() {
System.out.println("hello, i'm invoked by quartz.");
}
}
-applicationContext.xml
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/sch