1
+ package com .baeldung .restartjob ;
2
+
3
+ import org .springframework .batch .core .Job ;
4
+ import org .springframework .batch .core .Step ;
5
+ import org .springframework .batch .core .configuration .annotation .StepScope ;
6
+ import org .springframework .batch .core .job .builder .JobBuilder ;
7
+ import org .springframework .batch .core .repository .JobRepository ;
8
+ import org .springframework .batch .core .step .builder .StepBuilder ;
9
+ import org .springframework .batch .item .ItemProcessor ;
10
+ import org .springframework .batch .item .ItemWriter ;
11
+ import org .springframework .batch .item .file .FlatFileItemReader ;
12
+ import org .springframework .batch .item .file .builder .FlatFileItemReaderBuilder ;
13
+ import org .springframework .batch .item .file .mapping .PassThroughLineMapper ;
14
+ import org .springframework .context .annotation .Bean ;
15
+ import org .springframework .context .annotation .Configuration ;
16
+ import org .springframework .core .io .ClassPathResource ;
17
+ import org .springframework .transaction .PlatformTransactionManager ;
18
+
19
+ @ Configuration
20
+ public class BatchConfig {
21
+
22
+ @ Bean
23
+ public Job simpleJob (JobRepository jobRepository , PlatformTransactionManager transactionManager ) {
24
+ return new JobBuilder ("simpleJob" , jobRepository )
25
+ .start (step1 (jobRepository , transactionManager ))
26
+ .build ();
27
+ }
28
+
29
+ @ Bean
30
+ public Step step1 (JobRepository jobRepository , PlatformTransactionManager transactionManager ) {
31
+ return new StepBuilder ("step1" , jobRepository )
32
+ .<String , String >chunk (2 , transactionManager )
33
+ .reader (flatFileItemReader ())
34
+ .processor (itemProcessor ())
35
+ .writer (itemWriter ())
36
+ .build ();
37
+ }
38
+
39
+ @ Bean
40
+ @ StepScope
41
+ public FlatFileItemReader <String > flatFileItemReader () {
42
+ return new FlatFileItemReaderBuilder <String >()
43
+ .name ("itemReader" )
44
+ .resource (new ClassPathResource ("data.csv" ))
45
+ .lineMapper (new PassThroughLineMapper ())
46
+ .saveState (true )
47
+ .build ();
48
+ }
49
+
50
+ @ Bean
51
+ public ItemProcessor <String , String > itemProcessor () {
52
+ return item -> {
53
+ System .out .println ("Processing: " + item );
54
+
55
+ if (item .equals ("Item3" )) {
56
+ throw new RuntimeException ("Simulated failure on Item3" );
57
+ }
58
+
59
+ return "PROCESSED " + item ;
60
+ };
61
+ }
62
+
63
+ @ Bean
64
+ public ItemWriter <String > itemWriter () {
65
+ return items -> {
66
+ System .out .println ("Writing items:" );
67
+ for (String item : items ) {
68
+ System .out .println ("- " + item );
69
+ }
70
+ };
71
+ }
72
+ }
0 commit comments