logineimer
logineimer

Reputation: 73

Dynamic creation of Spring Batch jobs without XML

is it possible to setup Spring Batch without XML for jobs?

Currently, there are a lot of those job beans defined in XML:

<bean id="sampleJob" class="com.test.job.TestJob">
    <property name="idBase" value="SampleId" />
    <property name="targetTableName" value="SAMPLE_TABLE" />
    <property name="sql">
        <value><![CDATA[
        SELECT 42 FROM 1337
        ]]></value>
    </property>
</bean>

Spring Batch runs every night in our app. I want to make it possible to edit the job's properties. The idea is to get the injected properties from a database instead of hardcoding them in XML.

Please tell me if you've got a better idea how to solve the problem. Currently, I want to implement a kind of factory which provides a methode like that:

public TestJob createJob(String name) {
    String sql = db.getSqlFor(name);
    String table = db.getTableFor(name);
    ...
    return new TestJob(sql, table, ...);
}

Does Spring Batch offer these possibilites? I googled a lot but didn't find a satisfying solution.

Thanks in advance!

Upvotes: 4

Views: 6861

Answers (1)

Hansjoerg Wingeier
Hansjoerg Wingeier

Reputation: 4444

It is possible. just use the different builders provided by SpringBatch in order to create your job dynamically.

The steps and all reader and writer which they use don't have to be spring beans (of course, there will be no autowiring in this case, which forces you to do this yourself).

@Configuration
public class SimpleJobConfiguration {
    private static final String JOB_NAME = "SimpleTestJob";

    @Autowired
    private JobBuilderFactory jobs;

    @Autowired
    private StepBuilderFactory steps;


    @Bean
    public Job job() throws Exception {
        SimpleJobBuilder jobBuilder = this.jobs.get(createJobName(JOB_NAME)).start(firstStep());

        for ... {
            jobBuilder.next(createAStep( ... params ...));
        }

        return standardJob.build();
    }

    public Step createAStep(String name, ... needed parameters ...) throws Exception {
        StepBuilder stepBuilder = this.steps.get(name);

        build your step

        return standardStep1.build();
    }
}

Upvotes: 3

Related Questions