当前位置 : 首页 » 互动问答 » 正文

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

分类 : 互动问答 | 发布时间 : 2017-10-25 17:10:34 | 评论 : 1 | 浏览 : 32 | 喜欢 : 0

我有一个需要配置的弹簧批处理作业。从某种意义上说,它应该能够根据传递的内容读取不同的文件并构建读者,并且可能每个不同的读者都拥有自己的作者。下面的例子读取一个文件,我打电话给它的作者。我怎样才能让load_area.txt成为动态的

 @Bean
  public Step orderStep(){
      返回stepBuilderFactory.get(“loadAStep”)
              。<FieldSetter,FieldSetter>块(3)
              .reader(读取器())
              .processor(处理器())
              .writer(作家())
              。建立();
  }

  @豆
  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);
          }});
      }});
      回报阅读器;
  }

   @豆
  public ItemWriter <GenericFieldSetter> writer(){
    返回新的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)

  • 1楼
  • 您可以使用 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);
              }});
          }});
          回报阅读器;
      }

相关阅读: