繁体   English   中英

尝试在弹簧石英作业中注入时,@Autowired 字段中有 null?

[英]There is null in @Autowired field when try to inject in spring-quartz job?

有弹簧应用与 spring-batch 和弹簧石英一起使用

@Service class 启动 spring-batch 并命名为 MyService。

@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-quarts 作业和配置尝试注入此服务和启动方法 helloMethod() 如果作业仅包含记录器,则没有问题并且可以正常工作。

然后,我尝试将我的服务注入其中一个领域。 每次应用程序启动后,第一次作业包含此字段,但下一次此字段中有 null。

我试图通过 new 创建我的服务: MyService service = new MyService();

但在首次成功发射后,所有自动接线字段在使用中均为 null

应用部署在 webshere 8.5.5.13(2 个节点的集群)、oracle11g 和 spring4 上。 Java8。

然后,使用@Autowired注释将服务注入到作业中,该作业只运行一次。 在所有后续作业执行期间,注入的字段是 null。 此外,如果我在 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");

它解决了我的问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM