how to send a custom object as Job Parameter in Spring Batch?

ravinder reddy picture ravinder reddy · Nov 17, 2015 · Viewed 12.5k times · Source

I have a requirement of sending a Custom Object to the Spring Batch Job , where this Object is used continuously used by the Item Processor for the business requirement.

How can we send custom object from outside to the Job Context. This Object changes from Job to Job and generated at runtime depending on Business case.

How can send this as a Job Parameter? or is there any way that i can set this Object to the respective Job ?

can overriding Spring JobParameter help me in any way? or are there any Big issues as an outcome of this Overriding behaviour ?

Answer

manoj picture manoj · Jun 19, 2017

Use the below class to send CustomObject.

public static class CustomJobParameter<T extends Serializable> extends JobParameter {
        private T customParam;
        public CustomJobParameter(T customParam){
            super(UUID.randomUUID().toString());//This is to avoid duplicate JobInstance error
            this.customParam = customParam;
        }
        public T getValue(){
            return customParam;
        }
    }

===========================

Usage:

  1. Sending parameter:

    JobParameters paramJobParameters = new JobParametersBuilder().addParameter("customparam", new CustomJobParameter<MyClass>(myClassReference)).toJobParameters();

  2. Retrieving parameter:

    MyClass myclass = (MyClass)jobExecution.getJobParameters().getParameters().get("customparam").getValue();