我需要帮助来使用 Quartz 从数据库中检索数据。我正在从主类中的 config.xml 中读取休眠属性,并使用这些属性尝试从我的作业类 (Quartz Process.java) 中检索数据,该类正在获取空指针异常。
请帮助我解决问题。谢谢并提前
这是我的主要课程:
@Component("TestProgram")
public class TestProgram
{
static ClassPathXmlApplicationContext applicationContext=null;
public void testMethod() throws SchedulerException
{
JobDetail job = new JobDetail();
job.setName("Retriving The Master Details");
job.setJobClass(QuartzProcess.class);
SimpleTrigger trigger = new SimpleTrigger();
trigger.setName("Trigger For Retriving The Master Details");
trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
trigger.setRepeatInterval(5000);
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
}
public static void main(String[] args) throws Exception
{
String conf[] = {"Config.xml"};
applicationContext= new ClassPathXmlApplicationContext(conf);
TestProgram unittest=applicationContext.getBean(TestProgram.class);
unittest.testMethod();
}
}
石英工艺.java
@Component("QuartzProcess")
public class QuartzProcess implements Job
{
@Autowired
private MasterService MasterService;
@Override
public void execute(JobExecutionContext jec) throws JobExecutionException
{
try
{
List<MasterVO> MasterVO=MasterService.findAll();
System.out.println("MasterVO..."+MasterVO);
for(int index=0;index<MasterVO.size();index++)
System.out.println(MasterVO.get(index));
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
您收到 Null 指针异常,因为您的 Quartz 作业未由 Spring 实例化并且在 springContext 之外运行,因此您在其中引用的所有 bean 都将为 null。现在有几种方法可以访问石英 Job 中的 spring beans。
1)在applicationContext中定义下面的bean
在您的测试类中获取上述 bean 调度程序。您的测试类中的代码将如下所示:
您需要以通常的方式进入主类的调度程序 bean。您不需要执行 scheduler.start ,因为调度程序将由 spring 容器启动。
在您的 QuartzProcess 类中,您需要添加以下方法来获取 applicationContext:
然后在quartzprocess的xecute方法中,您需要执行以下代码来获取所需的bean