JobExecutionListenerSupport中的执行上下文键NULL

时间:2019-06-23 08:26:04

标签: java spring spring-batch

我正在使用下面的ItemWriteListener存储遇到的ID值。
我知道春季有StepJob上下文,因此我尝试使用 Job 上下文存储和检索值。

@JobScope
@Component
public class JobWriteNotificationListener implements ItemWriteListener<Retailer> {
    private ExecutionContext context;

    public JobWriteNotificationListener(StepExecution context) {
        this.context = context.getJobExecution().getExecutionContext();
        if (!this.context.containsKey(RETAILER_ID_KEY))
            this.context.put(RETAILER_ID_KEY, new HashSet<Integer>());
    }

    @SuppressWarnings("unchecked")
    private Set<Integer> get() {
        return (Set<Integer>) this.context.get(RETAILER_ID_KEY);
    }

    @Override
    public void afterWrite(List<? extends Retailer> list) {
        Set<Integer> set = get();
        list.forEach(id -> set.add(id.getId()));
    }
}

我正在尝试在afterJob侦听器中检索这些值。

@JobScope
@Component
public class JobCompletionNotificationListener extends JobExecutionListenerSupport {
    private static final Logger log = LoggerFactory.getLogger(JobCompletionNotificationListener.class);

    private final JdbcTemplate jdbcTemplate;

    public JobCompletionNotificationListener(
            JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void afterJob(JobExecution jobExecution) {
        @SuppressWarnings("unchecked") Set<Integer> added = (Set<Integer>) jobExecution.getExecutionContext().get(RETAILER_ID_KEY);
        if(jobExecution.getStatus() == BatchStatus.COMPLETED) {
            log.info("job completed {} :: added {}", jobExecution.getStatus(), added.size());
        }
    }
}

我的问题是在afterJob方法中,jobExecution.getExecutionContext().get(RETAILER_ID_KEY)引发了空引用异常。

从我所看到的,我同时使用了 Job 上下文?

1 个答案:

答案 0 :(得分:0)

在@JobScope中创建@Component,并将其注入到每个组件中。 它将在范围中共享。