您好,登錄后才能下訂單哦!
當我們使用spring boot整合schedule創建定時任務時,出現空指針,很有可能是因為配置定時任務類,創建job對象的時候,由于job工程接收到任務類創建對象是通過反射創建,通過放射創建的對象并不會將該對象放入spring容器,而在定時任務類進行注入業務類的時候無法注入。所以需要手動的將任務類對象放入spring容器中。
步驟:
1.定義創建任務類的類,并繼承AdaptableJobFactory,該類負責創建任務類對象,但是原始的類并沒有把創建好的類放入spring容器,所以需要重寫其中的方法手動將任務類放入spring容器。
2.將上一步創建的對象放入任務工廠對象中
附加:
定時類配置代碼
package com.example.quartz;
import org.quartz.CronScheduleBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;
@Configuration
public class QuartzConfig {
//創建job對象
@Bean
public JobDetailFactoryBean jobDetailFactoryBean(){
JobDetailFactoryBean factory = new JobDetailFactoryBean();
//factory接收到QuartzJob類對象后,通過反射方式創建對象,并沒有放入spring容器中。
factory.setJobClass(QuartzJob.class);
return factory;
}
//創建simple trigger對象
@Bean
public SimpleTriggerFactoryBean simpleTriggerFactoryBean(){
SimpleTriggerFactoryBean factory = new SimpleTriggerFactoryBean();
//關聯jobDetail對象
factory.setJobDetail(jobDetailFactoryBean().getObject());
//間隔毫秒數
factory.setRepeatInterval(2000);
//重復次數
return factory;
}
//創建crontrigger
@Bean
public CronTriggerFactoryBean cronTriggerFactoryBean(){
CronTriggerFactoryBean factory = new CronTriggerFactoryBean();
factory.setJobDetail(jobDetailFactoryBean().getObject());
factory.setCronExpression("0/1 * * * * ?");
return factory;
}
@Bean
public SchedulerFactoryBean schedulerFactoryBean(MyJobDetailFactoryBean myJobDetailFactoryBean){
SchedulerFactoryBean factory = new SchedulerFactoryBean();
//關聯trigger
factory.setTriggers(simpleTriggerFactoryBean().getObject());
//將前面的覆蓋掉。
factory.setTriggers(cronTriggerFactoryBean().getObject());
factory.setJobFactory(myJobDetailFactoryBean);
return factory;
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。