Skip to content

Job scoped steps are instantiated before the flow starts since 6.0.6, breaking late binding of jobExecutionContext #5680

Backlog

Description

@TDesjardins

Bug description

Since 6.0.6, FlowJob#doExecute calls warnOnDuplicateStepNames() before the flow starts. To collect the step names, it calls getName() on every step of the flow, including nested flows. For a @JobScope step, that call goes through the scoped proxy and creates the target bean right away.

As a result, a @JobScope step that gets a value from #{jobExecutionContext[...]} is now built when the job starts, before an earlier step has stored that value. The value is injected as null. Because the bean is then cached in the job scope, the step also runs with null later, not just during the duplicate check.

In 6.0.5 the same job works: job scoped steps were only created when the flow reached them.

Environment

    • Spring Batch 6.0.6 and 6.1.0 (with Spring Framework 7.1.0), works with 6.0.5
  • Spring Framework as managed by Spring Boot 4.1.2
  • Java 21
  • Default infrastructure of @EnableBatchProcessing (ResourcelessJobRepository)

Steps to reproduce

The test below passes with 6.0.5 and fails with 6.0.6. It needs only spring-batch-core and JUnit Jupiter.

package example;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Objects;

import org.junit.jupiter.api.Test;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobScope;
import org.springframework.batch.core.job.Job;
import org.springframework.batch.core.job.JobExecution;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.job.parameters.JobParameters;
import org.springframework.batch.core.launch.JobOperator;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.Step;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.infrastructure.repeat.RepeatStatus;
import org.springframework.batch.infrastructure.support.transaction.ResourcelessTransactionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;

class JobScopeLateBindingTest {

    @Test
    void jobScopedStepSeesValueStoredByPreviousStep() throws Exception {

        try(AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ReproducerConfiguration.class)) {

            JobOperator jobOperator = context.getBean(JobOperator.class);
            Job job = context.getBean("job", Job.class);

            JobExecution jobExecution = jobOperator.start(job, new JobParameters());

            assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus(), () -> "Failures: " + jobExecution.getAllFailureExceptions());

        }

    }

    @Configuration
    @EnableBatchProcessing
    static class ReproducerConfiguration {

        @Bean
        PlatformTransactionManager transactionManager() {
            return new ResourcelessTransactionManager();
        }

        @Bean
        Job job(JobRepository jobRepository, Step producerStep, Step consumerStep) {
            return new JobBuilder("job", jobRepository)
                    .flow(producerStep)
                    .next(consumerStep)
                    .end()
                    .build();
        }

        @Bean
        Step producerStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
            return new StepBuilder("producerStep", jobRepository)
                    .tasklet((contribution, chunkContext) -> {
                        contribution.getStepExecution().getJobExecution().getExecutionContext().put("value", "hello");
                        return RepeatStatus.FINISHED;
                    }, transactionManager)
                    .build();
        }

        @Bean
        @JobScope
        Step consumerStep(@Value("#{jobExecutionContext['value']}") String value, JobRepository jobRepository,
                PlatformTransactionManager transactionManager) {
            Objects.requireNonNull(value, "value must be set by producerStep");
            return new StepBuilder("consumerStep", jobRepository)
                    .tasklet((contribution, chunkContext) -> RepeatStatus.FINISHED, transactionManager)
                    .build();
        }

    }

}

Expected behavior

As in 6.0.5: consumerStep is created when the flow reaches it, value is "hello", and the job completes.

Actual behavior

consumerStep is created by warnOnDuplicateStepNames() before producerStep runs, value is null, and the job fails. Without the requireNonNull, the step would be built with null and keep that value for the whole job execution.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.consumerStep' defined in example.JobScopeLateBindingTest$ReproducerConfiguration: Failed to instantiate [org.springframework.batch.core.step.Step]: Factory method 'consumerStep' threw exception with message: value must be set by producerStep
	at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:657)
	...
	at org.springframework.batch.core.scope.JobScope.get(JobScope.java:107)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:369)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
	at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35)
	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:199)
	at jdk.proxy2/jdk.proxy2.$Proxy38.getName(Unknown Source)
	at org.springframework.batch.core.job.flow.support.state.StepState.getStepNames(StepState.java:85)
	at org.springframework.batch.core.job.flow.FlowJob.findSteps(FlowJob.java:128)
	at org.springframework.batch.core.job.flow.FlowJob.findDuplicateStepNames(FlowJob.java:93)
	at org.springframework.batch.core.job.flow.FlowJob.warnOnDuplicateStepNames(FlowJob.java:78)
	at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:171)
	at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:295)
	at org.springframework.batch.core.launch.support.TaskExecutorJobLauncher$1.run(TaskExecutorJobLauncher.java:207)
	...
Caused by: java.lang.NullPointerException: value must be set by producerStep
	at java.base/java.util.Objects.requireNonNull(Objects.java:259)
	at example.JobScopeLateBindingTest$ReproducerConfiguration.consumerStep(JobScopeLateBindingTest.java:81)

Notes

  • The comment in doExecute ("done at execution time, as the names of job/step scoped steps can only be resolved once the scope is active") suggests that resolving scoped steps here was intentional. Creating them as a side effect is the part that breaks late binding of jobExecutionContext.
  • The check was added for Not unique steps names in a FlowJob should log a warning #3757 in 6.1.0 and backported to 6.0.x (label for: backport-to-6.0.x). For a patch release, a warning-only check changing when beans are created is a surprising behavior change.
  • Possible directions: skip the check for scoped steps (or resolve their names without instantiating the target), make the check opt-in in 6.0.x, or run it after the flow has finished.

We worked around it by reading the values in the tasklet at execution time instead of injecting them into the @JobScope step. We are fine with that pattern, but other users relying on late binding in job scoped steps will hit the same failure after a patch upgrade.

Activity

  1. added
    status: waiting-for-triage
    on Nov 25, 2026
  2. added a commit that references this issue on Nov 26, 2026
    26c7720
  3. added 2 commits that reference this issue on Nov 26, 2026
    5c784e1
    6fe79f2
  4. thxwelchs commented on Nov 26, 2026

    @thxwelchs

    I opened #5682 for this. It skips scoped steps in the duplicate step name check, so job scoped steps are only created when the flow reaches them, like in 6.0.5.

    #5681 takes a different approach and runs the check after the flow. The PR description has a case where I think that could still create scoped steps on branches that were not taken. Happy to go with whichever direction you prefer.

  5. quaff commented on Nov 26, 2026

    @quaff
    Contributor

    I opened #5682 for this. It skips scoped steps in the duplicate step name check

    It breaks the feature.

  6. thxwelchs commented on Nov 26, 2026

    @thxwelchs

    Thanks for the feedback. When I opened #5682, my thinking was that the main problem here is the regression: jobs that worked on 6.0.5 now get null for late bound values. So I went with the smallest change I could find that brings back the 6.0.5 behavior, and I thought giving up the warning for scoped steps was acceptable for that, since it only means a log message is missing for them while everything else still runs as before.

    That said, you're right that it leaves out duplicates between scoped steps, which was part of the point of #3757. I think there might be a way to keep both. Since getting the name of a scoped step creates it, the check could be split in two:

    • non scoped steps are checked when the job starts, like today (all branches and nested flows)
    • scoped steps are checked when the flow reaches them and they are created anyway, against the step names seen so far

    This would keep late binding working, still report duplicates between scoped steps that actually run, and not create scoped steps on branches that are not taken. The gap left is scoped steps on branches that never run, but I don't see a way to get their names without creating them, and the warning is about restart, which only looks at steps that ran.

    If this sounds reasonable, I'll update #5682 in this direction. Happy to hear other ideas too.

  7. added
    for: backport-to-6.0.x
    and removed
    status: waiting-for-triage
    on Nov 26, 2026
  8. added this to the 6.1.1 milestone on Nov 26, 2026
  9. fmbenhassine commented on Nov 26, 2026

    @fmbenhassine
    Contributor

    Thank you for raising this, @TDesjardins. This is a regression, and the side effect of the back port to 6.0.x was not intended. Apologies for that. The reason we did not catch that case is that we don't have job-scoped steps that late-bind a jobExecutionContext in our test suite (we recommend plain steps, with step-scoped components instead, see #3900). That said, we still need to fix this regression, so I planned it for the next release.

    @quaff and @thxwelchs Thank you both for the follow up and for the PRs! While both PRs fix the issue, I found that each one has a limitation:

    I think we need like a combination of both, and I agree on the split proposed by @thxwelchs:

    • Non-scoped steps should be checked when the job starts, as today, including all branches and nested flows.
    • Scoped steps should be checked when the flow reaches them and they get created anyway, against the step names seen so far. The check must never create a scoped step itself.
    • A scoped step on a branch that is never taken is never named, so a duplicate there can't be reported. That is expected.

    The warning should behave the same for scoped and non-scoped steps, apart from that limitation.

    For tests, I think we need at least to cover the following cases: late binding of jobExecutionContext in a flow job, a scoped step on an untaken branch not being created, and a duplicate between scoped steps (or between a scoped and a non-scoped step) being reported. We also need to make sure a failure in the check can't fail the job.

    Could you please coordinate on a single PR (either of the two)? Otherwise, I will take care of the change and add you both as co-authors.

  10. thxwelchs commented on Nov 27, 2026

    @thxwelchs

    Thanks @fmbenhassine for the detailed review, that plan works for me. I'll update #5682 with this approach and cover the cases you listed.

    @quaff thanks for catching the missing check for scoped steps. The final change is really a combination of both PRs, so I'd like to add you as a co-author if that's okay with you. Your review on the update would be very welcome as well.

  11. quaff commented on Nov 27, 2026

    @quaff
    Contributor

    I will close GH-5681, leave it to @thxwelchs , but I have different thoughts.

    Non-scoped steps should be checked when the job starts, as today, including all branches and nested flows.

    Do we really need this? it introduce complexity make code unreadable.

    Scoped steps should be checked when the flow reaches them and they get created anyway, against the step names seen so far. The check must never create a scoped step itself.

    I think checking steps no matter it's scoped when the flow reaches them is enough.

    Also, the integration tests in GH-5681 should be included.

  12. fmbenhassine commented on Nov 27, 2026

    @fmbenhassine
    Contributor

    @quaff Thank you for the quick follow up!

    Non-scoped steps should be checked when the job starts, as today, including all branches and nested flows.

    Do we really need this? it introduce complexity make code unreadable.

    I think we do, as this was the goal of #3757 in the first place: warn the user before the job runs, for every step of the flow, including branches that may never be taken (the sooner the better). In the example of that issue, the job loops on the second step1, so a warning emitted only when the flow reaches that step would come too late (and a duplicate on an untaken branch would never be reported, although it can still break a later run or a restart).

    Scoped steps are the only exception. Their name can't be resolved without creating them, which is what broke late binding in 6.0.6, so they are checked when the flow reaches them. For a job without scoped steps, the behavior should stay as in #3757.

    When re-reviewing #5682, I will make sure we don't introduce any accidental complexity and try to keep things as simple as possible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    for: backport-to-6.0.xin: coretype: bug

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions