'How to modify job parameter on spring batch?

I've managed to get a job parameter context on a Tasklet but I didn't figure out how to change this value so the next Tasklet can access a modified value

val params = JobParametersBuilder()
    .addString("transaction", UUID.randomUUID().toString())
    .addDouble("amount", 0.0)

jobLauncher.run(
    paymentPipelineJob,
    params.toJobParameters()
)

First task:

override fun beforeStep(stepExecution: StepExecution) {
    logger.info("[$javaClass] - task initialized.")

    this.amount = stepExecution.jobParameters.getDouble("amount")

    // Prints 0.0
    logger.info("before step: ${this.amount}")
}

override fun afterStep(stepExecution: StepExecution): ExitStatus? {
    // Change the execution content to pass it to the next step
    stepExecution.jobExecution.executionContext.put("amount", this.amount!! + 3)

    // Still prints 0.0
    logger.info("after step: ${stepExecution.jobParameters.getDouble("amount")}")
    logger.info("[$javaClass] - task ended.")
    return ExitStatus.COMPLETED
}

How can I modify a job parameter so all the steps can access it?



Solution 1:[1]

While the execution context is a mutable object, job parameters are immutable. Therefore, it is not possible to modify them once the execution is launched.

That said, according to the code you shared, you are putting an attribute amount in the job execution context and expecting to see the modified value from the job parameters instance. This is a wrong expectation. The execution context and the job parameters are two distinct objects and are not "inter-connected".

Edit: Add suggestion about how to address the use case

You can use the execution context to share data between steps. You are already doing this in your example:

stepExecution.jobExecution.executionContext.put("amount", this.amount!! + 3)

Once that is done in a listener after step 1, you can get the value from the EC in a listener before step 2:

double amount = stepExecution.jobExecution.executionContext.get("amount");

Please check Passing Data to Future Steps from the reference documentation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1