@BeforeStep 注释方法未被调用

@BeforeStep annotated method not being called

我正在编写 spring 批处理作业。但是当加载这个实现了tasklet接口的Archive class时,注解@BeforeStep下的方法没有被调用。谁能帮我这个 ? 谢谢

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.annotation.BeforeStep;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.repeat.RepeatStatus;


    public class Archive implements Tasklet{
        @Override
        public RepeatStatus execute(StepContribution arg0, ChunkContext arg1)
                throws Exception {

            System.out.println("in execute method :)");
            return RepeatStatus.FINISHED;
        }

        @BeforeStep
        public void retrieveInterstepData(StepExecution stepExecution){
            JobExecution jobExecution = stepExecution.getJobExecution();
            ExecutionContext jobContext = jobExecution.getExecutionContext();

        }
    }

第一个解决方案 可以是从 execute 方法中提取 ExecutionContext,您有 ChunkContext 并根据需要使用它。

ExecutionContext jobContext = chunkContext.getStepContext()
                                    .getStepExecution()
                                    .getJobExecution()
                                    .getExecutionContext();

第二种解决方案可以实现StepExecutionListener并覆盖beforeStep方法。你会得到类似的东西:

public class Archive implements Tasklet, StepExecutionListener{
    @Override
    public RepeatStatus execute(StepContribution arg0, ChunkContext arg1)
                throws Exception {
        System.out.println("in execute method :)");
        return RepeatStatus.FINISHED;
    }

    @Override
    public void beforeStep(final StepExecution stepExecution) {
        JobExecution jobExecution = stepExecution.getJobExecution();
        ExecutionContext jobContext = jobExecution.getExecutionContext();
    }
}

我也遇到过类似的问题,我们就这样解决了。至于为什么 @BeforeStep 没有在 tasklet 上被调用,而是在 readersprocessorswriters 中,我不确定。

第三种解决方案:您可能没有将您的 tasklet 注册为侦听器,因此不会从一开始就调用带注释的方法。您可以在作业 xml 定义中提供 tasklet 引用作为侦听器,如下所示:

<job id="yourJob" > 
    <step id="step1">
            <tasklet ref="archive">
                <listeners>
                    <listener ref="archive" />
                </listeners>
            </
        </step>
</job> 

您还必须为您的存档 class 添加注释:

@Component("archive")
@Scope("step")