在一个 spring 应用程序中,我使用了一堆 spring-batch 和 spring-quartz
我有一个运行 spring-batch 任务的服务。服务名称 MyService,方法 helloMethod();
@Service
@EnableBatchProcessing
@EnableScheduling
public class MyService {
@Autowired
JobLauncher jobLauncher;
@Autowired
Job processExportJob;
public void helloMethod() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
JobParameters jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis())
.toJobParameters();
jobLauncher.run(processExportJob, jobParameters);
}
}
该服务使用运行预定作业的 spring-quartz 启动。MyJob 在仅使用控制台输出时工作正常。接下来,使用 @Autowired 注释,我将我的服务注入到一个作业中,它只运行一次。在所有后续时间中,在服务字段中 - null 此外,如果您创建的服务不使用 spring'a,
MyService service = new MyService();
那么已经在服务内部所有字段都将为空,我该如何克服呢?
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class MyJob implements Job {
@Autowired
private MyService service;
private static final String MESSAGE = "===================================QUARTZ TACT===================================";
private Logger logger = Logger.getLogger(getClass());
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
logger.log(Level.INFO, MESSAGE);
try {
service.helloMethod();
} catch (Exception e) {
e.printStackTrace();
logger.log(Level.ERROR, " Failed..");
logger.log(Level.ERROR, Arrays.toString(e.getStackTrace()));
}
}
}
我将回答第二个问题:
这里null无处不在,因为在通过new创建对象的时候,是脱离了上下文创建了一个对象,所以这个类中使用的所有sprig anntoations都不起作用。相反,您可以执行以下操作:
而在方法中,不是 MyService service = new MyService():
它基本上相当于 MyService 上的 @Autowired,只有当您获得 ApplicationContext 的 NPE 时,它很可能是您的石英配置问题。