복붙노트

[SPRING] 스프링 배치 (Spring Batch)의 ItemReader에서 작업 매개 변수에 액세스하는 방법

SPRING

스프링 배치 (Spring Batch)의 ItemReader에서 작업 매개 변수에 액세스하는 방법

이것은 내 job.xml의 일부입니다.

<job id="foo" job-repository="job-repository">
  <step id="bar">
    <tasklet transaction-manager="transaction-manager">
      <chunk commit-interval="1"
        reader="foo-reader" writer="foo-writer"
      />
    </tasklet>
  </step>
</job>

이것은 아이템 리더입니다.

import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("foo-reader")
public final class MyReader implements ItemReader<MyData> {
  @Override
  public MyData read() throws Exception {
    //...
  }
  @Value("#{jobParameters['fileName']}")
  public void setFileName(final String name) {
    //...
  }
}

이것은 Spring Batch가 실행 중에 말하고있는 것입니다 :

Field or property 'jobParameters' cannot be found on object of 
type 'org.springframework.beans.factory.config.BeanExpressionContext'

여기 뭐가 잘못 됐니? Spring 3.0에서 이러한 메커니즘에 대해 더 자세히 읽을 수있는 곳은 어디입니까?

해결법

  1. ==============================

    1.명시된 바와 같이 독자는 '단계'범위가되어야합니다. 이 작업은 @Scope ( "step") 주석을 통해 수행 할 수 있습니다. 주석을 독자에게 추가하면 다음과 같이 작동합니다.

    명시된 바와 같이 독자는 '단계'범위가되어야합니다. 이 작업은 @Scope ( "step") 주석을 통해 수행 할 수 있습니다. 주석을 독자에게 추가하면 다음과 같이 작동합니다.

    import org.springframework.batch.item.ItemReader;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    @Component("foo-reader")
    @Scope("step")
    public final class MyReader implements ItemReader<MyData> {
      @Override
      public MyData read() throws Exception {
        //...
      }
    
      @Value("#{jobParameters['fileName']}")
      public void setFileName(final String name) {
        //...
      }
    }
    

    이 범위는 기본적으로 사용할 수 없지만 일괄 XML 네임 스페이스를 사용하는 경우에 사용됩니다. 그렇지 않다면 스프링 배치에 다음을 추가하면 스프링 배치 문서에 따라 스코프를 사용할 수있게됩니다.

    <bean class="org.springframework.batch.core.scope.StepScope" />
    
  2. ==============================

    2.jobParameters를 사용할 수 있으려면 독자가 범위 '단계'로 독자를 정의해야한다고 생각하지만 주석을 사용하여 수행 할 수 있는지 확실하지 않습니다.

    jobParameters를 사용할 수 있으려면 독자가 범위 '단계'로 독자를 정의해야한다고 생각하지만 주석을 사용하여 수행 할 수 있는지 확실하지 않습니다.

    xml-config를 사용하면 다음과 같이됩니다.

    <bean id="foo-readers" scope="step"
      class="...MyReader">
      <property name="fileName" value="#{jobExecutionContext['fileName']}" />
    </bean>
    

    자세한 내용은 Spring Batch 문서를 참조하십시오.

    아마도 그것은 @Scope를 사용하고 xml-config에서 단계 범위를 정의하여 작동합니다.

    <bean class="org.springframework.batch.core.scope.StepScope" />
    
  3. ==============================

    3.단일 JavaConfig 클래스에서 ItemReader 인스턴스와 Step 인스턴스를 정의하려는 경우. 다음과 같이 @StepScope 및 @Value 주석을 사용할 수 있습니다.

    단일 JavaConfig 클래스에서 ItemReader 인스턴스와 Step 인스턴스를 정의하려는 경우. 다음과 같이 @StepScope 및 @Value 주석을 사용할 수 있습니다.

    @Configuration
    public class ContributionCardBatchConfiguration {
    
       private static final String WILL_BE_INJECTED = null;
    
       @Bean
       @StepScope
       public FlatFileItemReader<ContributionCard> contributionCardReader(@Value("#{jobParameters['fileName']}")String contributionCardCsvFileName){
    
         ....
       }
    
       @Bean
       Step ingestContributionCardStep(ItemReader<ContributionCard> reader){
             return stepBuilderFactory.get("ingestContributionCardStep")
                     .<ContributionCard, ContributionCard>chunk(1)
                     .reader(contributionCardReader(WILL_BE_INJECTED))
                     .writer(contributionCardWriter())
                     .build();
        }
    }
    

    트릭은 itemValer가 @Value ( "# {jobParameters [ 'fileName']}") 주석을 통해 주입되므로 null 값을 itemReader에 전달하는 것입니다.

    Tobias Flohre에게 감사의 말 : Spring Batch 2.2 - JavaConfig Part 2 : JobParameters, ExecutionContext 및 StepScope

  4. ==============================

    4.꽤 늦었지 만 @BeforeStep 메서드에 주석을 달아서이 작업을 수행 할 수도 있습니다.

    꽤 늦었지 만 @BeforeStep 메서드에 주석을 달아서이 작업을 수행 할 수도 있습니다.

    @BeforeStep
        public void beforeStep(final StepExecution stepExecution) {
            JobParameters parameters = stepExecution.getJobExecution().getJobParameters();
            //use your parameters
    }
    
  5. ==============================

    5.추가 예제를 보완하면 JavaConfig 클래스의 모든 작업 매개 변수에 액세스 할 수 있습니다.

    추가 예제를 보완하면 JavaConfig 클래스의 모든 작업 매개 변수에 액세스 할 수 있습니다.

    @Bean
    @StepScope
    public ItemStreamReader<GenericMessage> reader(@Value("#{jobParameters}") Map<String,Object> jobParameters){
              ....
    }
    
  6. ==============================

    6.작업을 실행하는 동안 Job 매개 변수를 다음과 같이 전달해야합니다.

    작업을 실행하는 동안 Job 매개 변수를 다음과 같이 전달해야합니다.

    JobParameters jobParameters= new JobParametersBuilder().addString("file.name", "filename.txt").toJobParameters();   
    JobExecution execution = jobLauncher.run(job, jobParameters);  
    

    표현식 언어를 사용하여 다음과 같이 값을 가져올 수 있습니다.

     #{jobParameters['file.name']}
    
  7. ==============================

    7.작업 매개 변수를 bean으로 올바르게 맵으로 선언 했습니까?

    작업 매개 변수를 bean으로 올바르게 맵으로 선언 했습니까?

    또는 실수로 파일 이름에 대한 getter가없는 JobParameters 객체를 실수로 인스턴스화 했습니까?

    표현 언어에 대한 자세한 내용은 Spring 문서에서 정보를 찾을 수 있습니다.

  8. from https://stackoverflow.com/questions/6078009/how-to-get-access-to-job-parameters-from-itemreader-in-spring-batch by cc-by-sa and MIT license