简体   繁体   中英

spring batch before step not getting called, need step execution context

In my spring batch workflow configuration I have item writer as follows:

@Bean
@Scope(value = "step", proxyMode = ScopedProxyMode.INTERFACES)
public ItemWriter<Price> skippedItemWriter(@Value("#{stepExecution.executionContext}") ExecutionContext executionContext) {
    return new SkippedItemWriter(executionContext);
}


public class SkippedItemWriter implements ItemWriter<Price>, StepExecutionListener {

    private static final Logger LOGGER = getLogger(SkippedItemWriter.class);

    private final ExecutionContext executionContext;
    private StepExecution stepExecution;

    public SkippedItemWriter(final ExecutionContext executionContext) {
        this.executionContext = executionContext;
    }

    @Override
    public void write(List<? extends Price> items) {

        if (CollectionUtils.isEmpty(items)) {
            return;
        }
        /blah 
    }

    @Override
    public void beforeStep(StepExecution stepExecution) {
        LOGGER.info("in beforeStep");
        this.stepExecution = stepExecution;
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        return null;
    }
}

my before step and after step are not getting called.

the beans must be step scoped.

I am trying to get hold of the publish count which I set in previous steps:

ExecutionContext context = stepContribution.getStepExecution().getJobExecution().getExecutionContext();
context.putInt((PUBLISH_COUNT.name()), 0);

I have tried returning SkippedItemWriter() instead of ItemWriter<T> but I get another proxy error.

I should add SkippedItemWriter is part of composite writer:

@Bean
@Scope(value = "step", proxyMode = ScopedProxyMode.INTERFACES)
public ItemWriter<Price> compositeWriter() {
    CompositeItemWriter<Price> itemWriter = new CompositeItemWriter<>();
itemWriter.setDelegates(Arrays.asList(
              skippedItemWriter(null)));

        return itemWriter;   }

The reason is that since your SkippedItemWriter is a delegate of a composite item writer, it is not automatically registered as a listener and this should be done manually. Here is an excerpt from the Intercepting Step Execution section of the docs:

If the listener is nested inside another component, it needs to be explicitly
registered (as described previously under "Registering ItemStream with a Step").

So you need to explicitly register the SkippedItemWriter as a listener in your step.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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