spring批处理在运行时读取不同的文件

时间:2017-10-25 17:10:34

标签: spring-batch reader

我有一个需要配置的弹簧批处理作业。从某种意义上说,它应该能够根据传递的内容读取不同的文件并构建阅读器,并且可能每个不同的阅读器都有自己的编写器。下面的示例读取一个文件,我调用它的编写器。如何使load_area.txt成为动态的。

   @Bean
  public Step orderStep() {
      return stepBuilderFactory.get("loadAStep")
              .<FieldSetter, FieldSetter> chunk(3)
              .reader(reader())
              .processor(processor())
              .writer(writer())
              .build();
  }

  @Bean
  public FlatFileItemReader<FieldSetter> reader() {
      FlatFileItemReader<FieldSetter> reader = new FlatFileItemReader<FieldSetter>();
      reader.setResource(new ClassPathResource("load_a.txt"));
      reader.setLineMapper(new DefaultLineMapper<GenericFieldSetter>() {{
          setLineTokenizer(new DelimitedLineTokenizer("|") {{
              setNames(new String[] { "sCode","cName"});
          }});
          setFieldSetMapper(new BeanWrapperFieldSetMapper<FieldSetter>() {{
              setTargetType(FieldSetter.class);
          }});
      }});
      return reader;
  }

   @Bean
  public ItemWriter<GenericFieldSetter> writer() {
    return new LoadAreaItemWriter();
  }

load_a.txt   22 | RRR

load_b.txt   AA | ABCDED | 123 | 0000

我想在运行时读取load_a.txt或load_b.txt,具体取决于传递的内容并编写自己的编写器。它有可能是.txt或任何类型。

FieldSetter.java有setter和getters

1 个答案:

答案 0 :(得分:0)

您可以使用jobExecutionContext / stepExecutionContext动态传递文件名。你的bean应该有@StepScope

这是您访问jobExecutionContext / stepExecutionContext

的方法
@Bean
 @StepScope
  public FlatFileItemReader<FieldSetter> reader("#{jobExecutionContext['fileName']}") final String fileName ,@Value("#{stepExecutionContext['fileName']}") String filename1) {
      FlatFileItemReader<FieldSetter> reader = new FlatFileItemReader<FieldSetter>();
      reader.setResource(new ClassPathResource(fileName));
      reader.setLineMapper(new DefaultLineMapper<GenericFieldSetter>() {{
          setLineTokenizer(new DelimitedLineTokenizer("|") {{
              setNames(new String[] { "sCode","cName"});
          }});
          setFieldSetMapper(new BeanWrapperFieldSetMapper<FieldSetter>() {{
              setTargetType(FieldSetter.class);
          }});
      }});
      return reader;
  }