Java 尝试注入spring quartz作业时,@Autowired字段中存在空值?
弹簧应用与弹簧批次和弹簧石英一起使用 有@Service类启动spring批处理并命名为MyServiceJava 尝试注入spring quartz作业时,@Autowired字段中存在空值?,java,spring,dependency-injection,quartz,Java,Spring,Dependency Injection,Quartz,弹簧应用与弹簧批次和弹簧石英一起使用 有@Service类启动spring批处理并命名为MyService @Service @EnableBatchProcessing @EnableScheduling public class MyService { @Autowired JobLauncher jobLauncher; @Autowired Job processExportJob; public void helloMethod() throw
@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);
}
}
SpringQuarts的作业和配置试图注入此服务并启动方法helloMethod()
若作业只包含记录器,那个么就并没有问题,工作正常
然后,我尝试将我的服务注入其中一个领域。每次应用程序启动后,第一次作业包含此字段,但下一次此字段中有null
我试图通过以下方式创建我的服务:
MyService service=newmyservice()
但在服务中,首次成功启动后,所有自动连接字段均为空
应用程序部署在Webhere8.5.5.13(具有2个节点的集群)、oracle11g和spring4上。Java8
然后,使用@Autowired
注释,我将服务注入到作业中,直到该作业只工作一次。在所有后续作业执行期间,注入的字段为空。
此外,如果我在spring之外创建服务:
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()));
}
}
}
从不同的地方来使用这个:
ApplicationContext springContext =
WebApplicationContextUtils.getWebApplicationContext(ContextLoaderListener.getCurrentWebApplicationContext().getServletContext());
Object bean = springContext.getBean("myService");
它解决了我的问题当创建带有作业和触发器的调度程序时,调度程序将在数据库中序列化。作业字段被标记为瞬态,所以它不会保存在数据库中。然后在需要使用时由new创建,但新创建对象不在applicationContext中。。