Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 902
ravinder reddy Avatar asked Nov 17 '15 16:11

ravinder reddy


People also ask

What are job parameters in Spring Batch?

JobParameters is a set of parameters used to start a batch job. JobParameters can be used for identification or even as reference data during the job run. They have reserved names, so to access them we can use Spring Expression Language.

What is JobExplorer in Spring Batch?

public interface JobExplorer. Entry point for browsing executions of running or historical jobs and steps.

What is JobRepository in Spring Batch?

What is a "Job Repository" in Spring Batch? "JobRepository" is the mechanism in Spring Batch that makes all this persistence possible. It provides CRUD operations for JobLauncher, Job, and Step instantiations.


2 Answers

I have summarized reasons why you cannot send object as JobParameter in this question. There are couple of ideas on that question how you can do it.

TL:TR: I think best way would be either to create table in DB which stores Object and pass id of that record as JobParameter or to serialize Object to json and pass it as String in job as JobParameter. If you go with second option be aware that string_val is stored in DB as varchar 250 so limit is 250 characters.

like image 191
Nenad Bozic Avatar answered Oct 25 '22 19:10

Nenad Bozic


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();

like image 24
manoj Avatar answered Oct 25 '22 17:10

manoj