[英]NullPointerException while deploying Quartz in Spring Boot
我正在嘗試將Quartz 2.2.1與Spring Boot一起使用。 我試圖聲明一個計划的任務,該任務應該將一些數據寫入文件中。 我的工作定義如下:
public class JobTask implements Job {
@Autowired
JobController controller;
@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
try {
controller.doPrintData();
} catch (Exception e) {
e.printStackTrace();
}
}
}
接着 :
public class StartJob {
public static void main(final String[] args) {
final SchedulerFactory factory = new StdSchedulerFactory();
Scheduler scheduler;
try {
scheduler = factory.getScheduler();
scheduler.start();
} catch (SchedulerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
scheduler = factory.getScheduler();
final JobDetailImpl jobDetail = new JobDetailImpl();
jobDetail.setName("My job");
jobDetail.setJobClass(JobTask.class);
final SimpleTriggerImpl simpleTrigger = new SimpleTriggerImpl();
simpleTrigger.setStartTime(new Date(System.currentTimeMillis() + 5000));
//simpleTrigger.setStartTime(dateOf(12, 58, 00,06,05,2016));
simpleTrigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
simpleTrigger.setRepeatInterval(5000);
simpleTrigger.setName("Trigger execution every 5 secondes");
scheduler.start();
scheduler.scheduleJob(jobDetail, simpleTrigger);
System.in.read();
if (scheduler != null) {
scheduler.shutdown();
}
} catch (final SchedulerException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
PS:我已經測試了我的控制器方法“ doPrintData”,它可以工作。 但是,當我將其放入面向javaNullPointerException的execute方法中時。
Spring Boot為您管理它。 刪除石英依賴項,僅創建具有計划執行的Service
:
@Service
public class JobScheduler{
@Autowired
JobController controller;
//Executes each 5000 ms
@Scheduled(fixedRate=5000)
public void performJob() {
controller.doPrintData();
}
}
並為您的應用程序啟用任務計划:
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class);
}
}
也可以看看:
您需要使用SpringBeanJobFactory來使用Spring的自動裝配的bean創建Job。
class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {
private transient AutowireCapableBeanFactory beanFactory;
public void setApplicationContext(final ApplicationContext context) {
beanFactory = context.getAutowireCapableBeanFactory();
}
@Override
public Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
final Object job = super.createJobInstance(bundle);
beanFactory.autowireBean(job); //the magic is done here
return job;
}
}
然后當你做
SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
scheduler = schedFact.getScheduler();
AutowiringSpringBeanJobFactory autowiringSpringBeanJobFactory = new AutowiringSpringBeanJobFactory();
autowiringSpringBeanJobFactory.setApplicationContext(applicationContext);
scheduler.setJobFactory(autowiringSpringBeanJobFactory);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.