如何在QuartzJobBean中注入Spring DAO类,我正在使用在Config类级别实例化的JobDetailFactoryBean。我正在使用Spring4 Quartz 2.2.1 Annotation方法
@Configuration
public class SchedulerConfig {
@Bean
public JobDetailFactoryBean jobDetailFactoryBean() {
JobDetailFactoryBean factory = new JobDetailFactoryBean();
factory.setJobClass(SchedulerService.class);
//Should I inject DAO here?
factory.setGroup("mygroup");
factory.setName("myjob");
return factory;
}
}
QuartzJobBean已扩展为执行
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Service
public class SchedulerService extends QuartzJobBean {
@Autowire
public SchedulerDAO schDAO;
protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException {
System.out.println("---SchedulerService .executeInternal ----");
try {
init(ctx.getJobDetail().getJobDataMap(),
ctx.getScheduler().getContext());
} catch (SchedulerException e) {
e.printStackTrace();
}
// I want to do DAO methods used here - how to do that?
// Can get access to DAO
schDAO.getSomeMethods();
}
}
答案 0 :(得分:0)
你的问题是Quartz对你的配置类一无所知,所以它不能自动装配一个未知的bean。 转到SchedulerConfig.java并将您的服务或DAO声明为自动装配,然后使用jobdata并映射此对象以便在Quartz中传递。然后你可以在Quartz的executeInternal方法中使用它。 例如
@Configuration
public class mplampla{
@Autowired
private YourDAO dao;
@Bean
public JobDetailFactoryBean jobDetailFactoryBean(){
JobDetailFactoryBean factory = new JobDetailFactoryBean();
Map<String,Object> map = new HashMap<String,Object>();
map.put("YourDAO", dao);
factory.setJobDataAsMap(map);
return factory;
}
}
然后在你的YourJob.java
中public class YourJob extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException {
JobDataMap dataMap = ctx.getJobDetail().getJobDataMap();
YourDAO dao = (YourDAO) dataMap.get("YourDAO");
dao.getMethods();
}
}
如果您使用@Service类和YourDAO类作为@Transational,请小心,您将收到有关未声明的Bean的错误。在这种情况下,您必须传递DAO的接口。