我想知道如何在Quartz中从外部传递实例变量?
下面是我想写的伪代码。如何将externalInstance传递给此Job?
public class SimpleJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { float avg = externalInstance.calculateAvg(); } }
您可以将您的实例放在schedulerContext中。要计划作业时,可以在执行以下操作之前:
getScheduler().getContext().put("externalInstance", externalInstance);
您的工作类别如下:
public class SimpleJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { SchedulerContext schedulerContext = null; try { schedulerContext = context.getScheduler().getContext(); } catch (SchedulerException e1) { e1.printStackTrace(); } ExternalInstance externalInstance = (ExternalInstance) schedulerContext.get("externalInstance"); float avg = externalInstance.calculateAvg(); } }
如果您使用的是Spring,那么您实际上可以使用spring的支持来注入整个applicationContext,就像在Link中回答的那样