I'm following the official Spring Batch starter guide. I have a basic question. I get an error, that the Bean JobRepository is not defined. The guide really never creates that bean. It is used in the importUserJob and step1. How is that possible? Shouldn't they create that Bean to configure the db etc.? This is the Code from the Guide. The full code can be found here.
@Configuration
public class BatchConfiguration {
// tag::readerwriterprocessor[]
@Bean
public FlatFileItemReader<Person> reader() {
return new FlatFileItemReaderBuilder<Person>()
.name("personItemReader")
.resource(new ClassPathResource("sample-data.csv"))
.delimited()
.names(new String[]{"firstName", "lastName"})
.fieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {{
setTargetType(Person.class);
}})
.build();
}
@Bean
public PersonItemProcessor processor() {
return new PersonItemProcessor();
}
@Bean
public JdbcBatchItemWriter<Person> writer(DataSource dataSource) {
return new JdbcBatchItemWriterBuilder<Person>()
.itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
.sql("INSERT INTO people (first_name, last_name) VALUES (:firstName, :lastName)")
.dataSource(dataSource)
.build();
}
@Bean
public Job importUserJob(JobRepository jobRepository,
JobCompletionNotificationListener listener, Step step1) {
return new JobBuilder("importUserJob", jobRepository)
.incrementer(new RunIdIncrementer())
.listener(listener)
.flow(step1)
.end()
.build();
}
@Bean
public Step step1(JobRepository jobRepository,
PlatformTransactionManager transactionManager, JdbcBatchItemWriter<Person> writer) {
return new StepBuilder("step1", jobRepository)
.<Person, Person> chunk(10, transactionManager)
.reader(reader())
.processor(processor())
.writer(writer)
.build();
}
}
`
Thanks.
JobRepository
will be auto-configured as soon as you add the dependency:
org.springframework.boot:spring-boot-starter-batch
This will also create a few tables in the database configured for your application. Like BATCH_JOB_EXECUTION
and BATCH_STEP_EXECUTION
.
After proper auto-configuration JobRepositoty
bean can be autowired in any component or configuration class. Also as a constructor parameter like in your code snippet of BatchConfiguration
.