感谢Luca Basso Ricci 提供JobExecutionListener 指针。我最终创建了自己的StepExecutionListener,我的预处理将在其中进行。
我关注了this example from Mkyong,它涵盖了不同类型的 Spring Batch 侦听器。
我在 Java 代码中创建了一个像这样的自定义侦听器:
public class CustomStepListener implements StepExecutionListener {
@Autowired
private CustomObject customObject;
@Override
public void beforeStep(StepExecution stepExecution) {
// initialize customObject and do other pre set setup
}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
return null;
}
我在这里初始化了自动连线的CustomObject 类。 CustomObject 类是一个自定义对象,它只包含我的 List 类型 ComplexType。
@Component
public class CustomObject {
private List<ComplexType> customObjectList;
public List<ComplexType> getCustomObjectList() {
return customObjectList;
}
public void setCustomObjectList(List<ComplexType> customObjectList) {
this.customObjectList= customObjectList;
}
}
最后,在我的作业配置“batch-job-context.xml”中,我添加了新的监听器:
<!-- ... -->
<beans:bean id="customStepListener"
class="com.robotsquidward.CustomStepListener"/>
<job id="robotsquidwardJob"
job-repository="jobRepository"
incrementer="runIdIncrementer">
<step id="robotsquidwardStep">
<tasklet task-executor="taskExecutor" throttle-limit="1">
<chunk
reader="robotsquidwardReader"
processor="robotsquidwardProcessor"
writer="robotsquidwardWriter"
commit-interval="1"/>
</tasklet>
<listeners>
<listener ref="customStepListener"/>
</listeners>
</step>
</job>
当我按照这些步骤操作时,我能够在 beforeJob 函数中初始化我的 ComplexObject List 并在我工作的 Reader 类中访问 ComplexObject List 的值:
@Component
@Scope(value = "step")
public class RobotsquidwardReader implements ItemReader<ComplexType> {
@Autowired
private CustomObject customObject;
@Override
public ComplexType read() throws Exception, UnexpectedInputException,
ParseException, NonTransientResourceException {
if(customObject.getCustomObjectList() != null) {
return customObject.getCustomObjectList.remove(0);
} else {
return null;
}
}
}
就这么简单。只需要两个新类、一个配置更改和一个令人头疼的问题:)