我使用DAO服务实现Quartz作业,如下所示:
public class InitialFetchFrequenceScheduleJob implements Job
{
@Autowired
private FetchFrequencyService fetchFrequencyService;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException
{
try
{
List<FetchFrequency> frequencies = this.fetchFrequencyService.findAll(FetchFrequency.class);
问题是,当调用execute()方法时,this.fetchFrequencyService.findAll(FetchFrequency.class);
将抛出NPE,因为fetchFrequenceService为null。我这里做错了什么?任何回复都非常感谢。谢谢!
P / s我使用的是Quartz 2.1.7
更新:这是FetchFrequencyServiceImpl:
@Service("fetchFrequencyService")
public class FetchFrequencyServiceImpl extends GenericDaoImpl implements FetchFrequencyService
{
}
更新:代码实现工作:
JobDetail job = JobBuilder.newJob(InitialFetchFrequenceScheduleJob.class).build();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 1);
Trigger trigger = TriggerBuilder.newTrigger().forJob(job).startAt(cal.getTime()).build();
Scheduler scheduler = new StdSchedulerFactory("quartz.properties").getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
答案 0 :(得分:6)
@Autowired
在Quartz作业实现中不起作用,因为它不会被Spring实例化。为了在Quartz作业中掌握Spring托管的bean,首先应该使用org.springframework.scheduling.quartz.SchedulerFactoryBean
来管理Quartz生命周期。使用此FactoryBean,您可以指定applicationContextSchedulerContextKey
属性以在调度程序上下文中引用提供给Quartz作业的ApplicationContext,例如:
<bean id="scheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="applicationContextSchedulerContextKey" value="applicationContext" />
<!-- additional properties here -->
</bean>
您现在可以在作业中检索ApplicationContext
引用,然后从ApplicationContext
显式获取bean引用:
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
ApplicationContext applicationContext = (ApplicationContext) executionContext
.getScheduler().getContext().get("applicationContext");
FetchFrequencyService service = applicationContext.getBean(FetchFrequencyService.class);
// Start using your service.
}
答案 1 :(得分:1)
答案 2 :(得分:0)
使用:
SpringBeanAutowiringSupport.processInjectBasedOnCurrentContext(this)
在您的石英作业中自动装配您的bean
答案 3 :(得分:-1)
您必须使用以下注释之一注释您的类
表示DAO
@Repository
服务
@服务
controlloer
@Controller
所以你的服务类应该有以下注释。
@Service("fetchFrequencyService")
public Class FetchFrequencyService {
}
我需要将应用程序上下文注入SchedulerFactoryBean
<bean id="scheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean"
lazy-init="false">
<property name="jobFactory">
<bean class="org.springframework.scheduling.quartz.SpringBeanJobFactory" />
</property>
<property name="applicationContextSchedulerContextKey">
<value>applicationContext</value>
</property>
</bean>