gpt4 book ai didi

java - 通过 Spring Batch 作业步骤维护作业前对象

转载 作者:行者123 更新时间:2023-12-01 09:50:57 26 4
gpt4 key购买 nike

对于我的批处理应用程序,在执行 Spring Batch 作业之前我需要执行一些步骤。例如,我需要执行特定查询并将数据存储在属性中 - 具有复杂类型的列表 ( List<ComplexType> ) - 以便可以在整个 Spring Batch 作业中使用和操作它(主要在 ItemReader 中)。

我已尝试在列表中 Autowiring 并在步骤中访问它,但我无法以这种方式访问​​列表中的数据。无论在作业之前将什么值添加到我的 Autowiring 列表属性中,我的列表中都会出现空的 ComplexType。

我也尝试过passing data using ExecutionContext ,但我认为这不应该在 Spring Batch 作业执行之外工作。

我想知道的是,在执行 Spring Batch 作业之前填充项目并在整个作业生命周期中维护该对象的最佳方法是什么。

如果最好的方法是我之前所做的尝试之一,那么对于这些​​方法的常见错误的任何指导都将受到赞赏,谢谢。

最佳答案

谢谢Luca Basso Ricci对于 JobExecutionListener 指针。我最终创建了自己的 StepExecutionListener,我的预处理将在其中进行。

我关注了this example from Mkyong它涵盖了不同类型的 Spring Batch Listener。

我在 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;
}

我在这里初始化了 Autowiring 的 CustomObject 类。 CustomObject 类是一个自定义对象,仅包含我的 ComplexType 类型的 List

@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;
}
}
}

就这么简单。所需要的只是两个新类、一个配置更改和一个令人头疼的问题:)

关于java - 通过 Spring Batch 作业步骤维护作业前对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37601843/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com