Beliebte Suchanfragen

Cloud Native



Agile Methoden



Spring Batch 2.2 – JavaConfig Part 4: Job inheritance

22.6.2013 | 7 minutes of reading time

One important feature in XML is the possibility to write abstract job definitions like these:

1<job id="abstractJob" abstract="true">
2        <listeners>
3            <listener ref="commonJobExecutionListener"/>
4        </listeners>
5    </job>

Concrete job definitions may inherit parts of their definition from it:

1<job id="myJob" parent="abstractJob">
2        ...
3    </job>

In enterprise environments it’s often necessary to define common functionality, for example a common job protocol, common logging or common return code mapping, but of course there are many more use cases. You achieve this by registering certain listeners, and with the parent functionality above, it’s easy to register listeners in an abstract job. And often you have very similar jobs in a certain line of business that share more than just listeners, maybe they have the same reader and writer, or the same skip policy etc. In XML you extract this common stuff to abstract job definitions. How can you achieve this with Java based configuration? What are the advantages / disadvantages?
This is the fourth post about the new Java based configuration features in Spring Batch 2.2. Previous posts are about a comparison between the new Java DSL and XML , JobParameters, ExecutionContexts and StepScope and profiles and environments . Future posts will be about modular configurations and partitioning and multi-threaded step , everything regarding Java based configuration, of course. You can find the JavaConfig code examples on Github .

Builders and builder factories

There’s no direct equivalent to abstract job definitions in Java based configuration. But we have builders for jobs and steps, and we can prepare them with default functionality. If you look at the JobBuilderFactory in Spring Batch 2.2, you see that it creates a JobBuilder and calls the method repository on it:

1public class JobBuilderFactory {
3    private JobRepository jobRepository;
5    public JobBuilderFactory(JobRepository jobRepository) {
6        this.jobRepository = jobRepository;
7    }
9    public JobBuilder get(String name) {
10        JobBuilder builder = new JobBuilder(name).repository(jobRepository);
11        return builder;
12    }

That’s exactly how you implement job inheritance in Java based configuration: create a custom builder factory for your job or step and add the default functionality by calling the appropriate methods on the builder. The following CustomJobBuilderFactory allows for adding JobExecutionListeners to a JobBuilder.

1public class CustomJobBuilderFactory extends JobBuilderFactory {
3    private JobExecutionListener[] listeners;
5    public CustomJobBuilderFactory(JobRepository jobRepository, JobExecutionListener... listeners) {
6        super(jobRepository);
7        this.listeners = listeners;
8    }
10    @Override
11    public JobBuilder get(String name) {
12        JobBuilder jobBuilder = super.get(name);
13        for (JobExecutionListener jobExecutionListener: listeners){
14            jobBuilder = jobBuilder.listener(jobExecutionListener);
15        }
16        return jobBuilder;
17    }

Configuration with delegation

Now that we have our custom job builder factory, how do we use it? We create a common configuration class that contains the listener we want to add to every job, and the factory, of course:

2public class CommonJobConfigurationForDelegation {
4    @Autowired
5    private JobRepository jobRepository;
7    @Bean
8    public CustomJobBuilderFactory customJobBuilders(){
9        return new CustomJobBuilderFactory(jobRepository, protocolListener());
10    }
12    @Bean
13    public ProtocolListener protocolListener(){
14        return new ProtocolListener();
15    }

You can tell by its name that it should be included by delegation in concrete job configurations like this:

3public class DelegatingConfigurationJobConfiguration{
5    @Autowired
6    private CommonJobConfigurationForDelegation commonJobConfiguration;
8    @Bean
9    public Job delegatingConfigurationJob(){
10        return commonJobConfiguration.customJobBuilders()
11                .get("delegatingConfigurationJob")
12                .start(step())
13                .build();
14    }
16    ...

Why delegation? As you might know, there are two ways in Java to call common functionality: either you do it by delegating to an object that performs the logic, or you inherit the functionality from a super class. In the case above we use delegation, because we don’t inherit from CommonJobConfigurationForDelegation, we just import it and delegate the creation of the JobBuilder to its method customJobBuilders. In general I prefer delegation over inheritance because it isn’t as strict as inheritance, and classes aren’t so tightly coupled then. We may just extend one class, but we may delegate to as many objects as we want.
But let’s compare the Java configuration to the XML configuration now. The approaches are technically very different, though they achieve the same. In XML we define abstract Spring bean definitions that are completed with the information in the concrete job definition. In Java we prepare a builder with some default calls, and the concrete job is created with the prepared builder. First thing you notice: the Java approach is much more natural with less Spring magic in it. Now let’s assume that the parent functionality resides in some common library, in our case either the XML file with the abstract job definition or the class CommonJobConfigurationForDelegation. The common library is added as a Maven dependency. Let’s see how everyday’s handling differ:
XML: In Eclipse you cannot open the parent XML with the ‘Open resource’ shortcut, you have to search it by hand in the dependencies. And even if you find it, there’s no direct connection between the concrete and parent job definition, you have to do a full text search in the parent XML to find it.
Java: You just take the class with the concrete job definition and do ‘Open implementation’ on the method customJobBuilders, and you jump directly to the place where the common stuff is defined.
The advantages are obvious, aren’t they?

Configuration with inheritance

I said I prefer delegation over inheritance, but that doesn’t mean that there aren’t valid use cases for inheritance. Let’s take a look at a configuration class designed for inheritance:

1public abstract class CommonJobConfigurationForInheritance {
3    @Autowired
4    private JobRepository jobRepository;
6    @Autowired
7    private PlatformTransactionManager transactionManager;
9    @Autowired
10    private InfrastructureConfiguration infrastructureConfiguration;
12    protected CustomJobBuilderFactory customJobBuilders(){
13        return new CustomJobBuilderFactory(jobRepository, protocolListener());
14    }
16    protected CustomStepBuilderFactory<Partner,Partner> customStepBuilders(){
17        return new CustomStepBuilderFactory<Partner,Partner>(
18                jobRepository,
19                transactionManager,
20                completionPolicy(),
21                reader(),
22                processor(),
23                writer(),
24                logProcessListener());
25    }
27    @Bean
28    public CompletionPolicy completionPolicy(){
29        return new SimpleCompletionPolicy(1);
30    }
32    public abstract ItemProcessor<Partner,Partner> processor();
34    @Bean
35    public FlatFileItemReader<Partner> reader(){
36        FlatFileItemReader<Partner> itemReader = new FlatFileItemReader<Partner>();
37        itemReader.setLineMapper(lineMapper());
38        itemReader.setResource(new ClassPathResource("partner-import.csv"));
39        return itemReader;
40    }
42    @Bean
43    public LineMapper<Partner> lineMapper(){
44        DefaultLineMapper<Partner> lineMapper = new DefaultLineMapper<Partner>();
45        DelimitedLineTokenizer lineTokenizer = new DelimitedLineTokenizer();
46        lineTokenizer.setNames(new String[]{"name","email","gender"});
47        lineTokenizer.setIncludedFields(new int[]{0,2,3});
48        BeanWrapperFieldSetMapper<Partner> fieldSetMapper = new BeanWrapperFieldSetMapper<Partner>();
49        fieldSetMapper.setTargetType(Partner.class);
50        lineMapper.setLineTokenizer(lineTokenizer);
51        lineMapper.setFieldSetMapper(fieldSetMapper);
52        return lineMapper;
53    }
55    @Bean
56    public ItemWriter<Partner> writer(){
57        JdbcBatchItemWriter<Partner> itemWriter = new JdbcBatchItemWriter<Partner>();
58        itemWriter.setSql("INSERT INTO PARTNER (NAME, EMAIL) VALUES (:name,:email)");
59        itemWriter.setDataSource(infrastructureConfiguration.dataSource());
60        itemWriter.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<Partner>());
61        return itemWriter;
62    }
64    @Bean
65    public ProtocolListener protocolListener(){
66        return new ProtocolListener();
67    }
69    @Bean
70    public LogProcessListener logProcessListener(){
71        return new LogProcessListener();
72    }

We have two builder factories, one for the job and one for the step. They are protected and may be used by a subclass. If you’re interested in the implementation of the CustomStepBuilderFactory, take a look at Github . The builder factories use a lot of the components defined in this configuration class. The processor has an abstract definition, so a subclass has to add a processor. All the other components may be overridden by a subclass if needed. Let’s take a look at such a subclass.

2public class InheritedConfigurationJobConfiguration extends CommonJobConfigurationForInheritance{
4    @Bean
5    public Job inheritedConfigurationJob(){
6        return customJobBuilders().get("inheritedConfigurationJob")
7                .start(step())
8                .build();
9    }
11    @Bean
12    public Step step(){
13        return customStepBuilders().get("step")
14                .faultTolerant()
15                .skipLimit(10)
16                .skip(UnknownGenderException.class)
17                .listener(logSkipListener())
18                .build();
19    }
21    @Override
22    @Bean
23    public ItemProcessor<Partner, Partner> processor() {
24        return new ValidationProcessor();
25    }
27    @Override
28    @Bean
29    public CompletionPolicy completionPolicy() {
30        return new SimpleCompletionPolicy(3);
31    }
33    @Bean
34    public LogSkipListener logSkipListener(){
35        return new LogSkipListener();
36    }

So, what do we have here? This concrete configuration class implements the processor method, of course. Furthermore it overrides the definition of the CompletionPolicy. And then it uses the builder factories to create the job and the step, and it adds fault tolerance to the step.
Let’s take a look at the advantages / disadvantages. The coupling between parent and concrete definition is very tight, but in this case it’s fine. We want the parent to define needed components (the abstract method) and overridable default components (the other methods), and you cannot do this with delegation. Of course you may just inherit from one parent class. You use this pattern if you clearly want such a tight coupling, for example if you have a lot of very similar jobs that share the same type of components. In general you should only have one level of inheritance, take it as a bad smell and warning sign if there are more! Of course it’s always possible to combine delegation and inheritance.


Inheritance between jobs is important in enterprise environments. It’s achievable in XML and in Java based configuration in very different technical ways. The Java way may be a little bit more verbose, but has a lot of advantages that I pointed out in the paragraphs above.

share post




Gemeinsam bessere Projekte umsetzen.

Wir helfen deinem Unternehmen.

Du stehst vor einer großen IT-Herausforderung? Wir sorgen für eine maßgeschneiderte Unterstützung. Informiere dich jetzt.

Hilf uns, noch besser zu werden.

Wir sind immer auf der Suche nach neuen Talenten. Auch für dich ist die passende Stelle dabei.