接上文
SpringBoot+Quartz定时框架(Demo)
1.自定类
public class UserService {
public void testMethod(){
System.out.println("UserService.testMethod");
}
}
2.定时任务类中调用测试方法
import com.example.demo.pojo.UserService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
/**
* 定时任务类
*/
public class QuartzDemo implements Job {
//注入自定类
@Autowired
private UserService userService;
/**
* 任务被触发时所执行的方法
* @param context
* @throws JobExecutionException
*/
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
//调用自定类测试方法
this.userService.testMethod();
}
}
3.控制台报错
java.lang.NullPointerException: null
at com.example.demo.quartz.QuartzDemo.execute(QuartzDemo.java:25) ~[classes/:na]
at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ~[quartz-2.2.1.jar:na]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) [quartz-2.2.1.jar:na]
由报错可知UserService对象未注入,查看源码得知
//1.创建job对象
@Bean
public JobDetailFactoryBean jobDetailFactoryBean() {
JobDetailFactoryBean factoryBean