Skip to content
Advertisement

Spring Batch @BeforeContext Fails to Execute

I have a situation in spring batch where I have multiple item processors that make up a composite item processor. I need to share some context data between two processors in the same step. I have found a working solution to access the context, shown below. That said there is an alternate solution that appears to be a bit cleaner but it uses the @BeforeStepAnnotation, which never gets called. I would like to use the second solution if possible. Any advice on how to do this is much appreciated.

This works:

@Component
@StepScope
public class MyItemProcessor implements ItemProcessor<String,String> {

   @Value(#{stepExecution});
   private StepExecution stepExecution;


   public String process(String s){
     //Do things

     Context context = new Context();
     context.set("Hello Context");

     ExecutionContext executionContext = stepExecution.getExecutionContext();
     executionContext.put("Context", context);

   }

}

This fails:

@Component
@StepScope
public class MyItemProcessor implements ItemProcessor<String,String> {

   private ExecutionContext executionContext;

   public String process(String s){
      //Do things
      Context context = new Context();
      context.set("Hello Context");

      executionContext.put("Context", context);
   } 


   @BeforeStep
   public getCurrentContext(StepExecution stepExecution){
         executionContext = stepExecution.getExecutionContext();
   } 

}

Advertisement

Answer

Since your item processor is part of a composite, it is not introspected for @BeforeStep annotation and hence it is not registered as a listener. Spring Batch will only introspect the object that is registered as a processor (the composite in your case) and not the entire object graph.

You need to register any composing processor as a listener for this to work. The following links might help:

Advertisement