JuISe
JuISe

Reputation: 45

Dynamically create Job in Spring Batch

Is it possible to create Spring Batch Job dynamically as not a bean?

I have created a lot of readers, writers, processors and another tasklets and I would like to have a possibility to build Job at runtime from these parts.

I have some Job descriptions files in my xml-based format, saved in some directory. These Job descriptions can contain dynamic information about Job, for example, what reader and writer chose for this job. When the program starts, these files are parsed, and corresponding Jobs must be created.

I think to implement it like this:

@Autowired
private JobBuilderFactory jobBuilderFactory;

@Autowired
private StepBuilderFactory stepBuilderFactory;

@Autowired
private ApplicationContext context;

public Job createJob(MyXmlJobConfig jobConfig) {

    // My predefined steps in context

    Step initStep = context.getBean("InitStep", Step.class);

    Step step1 = context.getBean("MyFirstStep", Step.class);
    Step step2 = context.getBean("MySecondStep", Step.class);
    //......

    // Mix these steps to build job

    JobBuilder jobBuilder = jobBuilderFactory.get("myJob");
    SimpleJobBuilder simpleJobBuilder = jobBuilder.start(initStep);


    // Any logic of steps mixing and choosing
    if(jobConfig.somePredicate())
        simpleJobBuilder.next(step1);
    else
        simpleJobBuilder.next(step2);
    //.........


    //.......

    return simpleJobBuilder.build();
}

Usage example:

JobLauncher jobLauncher = context.getBean(JobLauncher.class);
MyXmlJobConfig config = getConfigFromFile(); // Loading config from file

MyCustomJobBuilder myCustomJobBuilder = context.getBean(MyCustomJobBuilder.class);
Job createdJob = myCustomJobBuilder.createJob(config);
jobLauncher.run(createdJob, new JobParameters());

Is this approach of job building correct? Note that the createdJob is not a bean. Will not it break anything of Spring Batch behind the scenes?

Upvotes: 1

Views: 3277

Answers (1)

Michael Minella
Michael Minella

Reputation: 21463

Spring Batch uses the Spring DI container and related facilities quite extensively. Proxying beans that are job or step scoped is just one example. The whole parsing of an XML based definition results in BeanDefinitions. Can you build a Spring Batch job without making it a bean? Sure. Would I recommend it? No.

Do keep in mind that there are ways of dynamically creating child ApplicationContext instances that you can have a job in. Spring Batch Admin and Spring XD both took advantage of this feature to dynamically create instances of Spring Batch jobs. I'd recommend this approach over having the job not part of an ApplicationContext in the first place.

Upvotes: 2

Related Questions