Legendary_Hunter
Legendary_Hunter

Reputation: 1080

Retrying reader in spring Batch

I have written a spring batch application and item reader is throwing exception. How do I retry item reader? I h ave added @EnableRetry on application class and below is the reader code

@Bean
  @Retryable(include = { RuntimeException.class }, maxAttempts = 1000, backoff = @Backoff(delay = 0))
  public ItemReader<Student> reader() {
    return new InMemoryStudentReader();
  }

Below is the reader class

public class InMemoryStudentReader implements ItemReader<Student> {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  private int nextStudentIndex;
  private List<Student> studentData;

  public InMemoryStudentReader() {
    initialize();
  }


  private void initialize() {
    Student s1 = new Student(1, "ABC");
    Student s2 = new Student(2, "DEF");
    Student s3 = new Student(3, "GHI");

    studentData = Collections.unmodifiableList(Arrays.asList(s1, s2,s3));
    nextStudentIndex = 0;
  }

  @Override
  public Student read() throws Exception {
    Student nextStudent = null;

    if (nextStudentIndex < studentData.size()) {
      int a =jdbcTemplate.queryForObject("SELECT id FROM val LIMIT 1", Integer.class);
      if(a == 2) {
        throw new RuntimeException("Exception");
      }
      nextStudent = studentData.get(nextStudentIndex);
      nextStudentIndex++;
    } else {
      nextStudentIndex = 0;
    }

    return nextStudent;
  }
}

But even after this the reader is not retried and job fails

Upvotes: 0

Views: 1394

Answers (1)

Mahmoud Ben Hassine
Mahmoud Ben Hassine

Reputation: 31600

You are adding @Retryable on a bean definition method. This method is only called at configuration time by Spring to create an instance of your bean and will unlikely fail.

You should be adding the annotation on the read method of your reader which is called at runtime when the step is running and might throw an exception:

@Override
@Retryable(include = { RuntimeException.class }, maxAttempts = 1000, backoff = @Backoff(delay = 0))
public Student read() throws Exception {
   ...
}

Upvotes: 1

Related Questions