[英]Spring Batch FlatFileItemReader populating field value across all items/lines read
I am reading a flat file using spring batch FlatFileItemReader
. 我正在使用春季批处理
FlatFileItemReader
读取平面文件。
I have a requestId
field which i need to populate with a unique value for all records read from the flat file. 我有一个
requestId
字段,我需要为从平面文件读取的所有记录填充一个唯一值。 eg: When i read file1. 例如:当我读取file1时。 I want to set the
requestId
to 1 for all Item objects created at requestId field. 我想将在requestId字段中创建的所有Item对象的
requestId
设置为1。 For file2, i need to set requestId to 2. 对于file2,我需要将requestId设置为2。
my requestId is uniquely generated by a separate class. 我的requestId是由一个单独的类唯一生成的。
How can I achieve this using spring batch? 如何使用Spring Batch实现此目的?
there are some possible solutions 有一些可能的解决方案
use an ResourceAware Item 使用ResourceAware项
public class MyItem implements ResourceAware {
private Resource resource;
public String getId() {
return createIdFromResource(resource);
}
private String createIdFromResource(final Resource resource) {
// create your ID here
return resource.getFilename();
}
@Override
public void setResource(final Resource resource) {
this.resource = resource;
}
}
use an Listener (here with interfaces, less verbose use of annotations is possible too) 使用侦听器 (在这里使用接口,也可以减少冗长的注释使用)
public class TestListener implements StepExecutionListener, ItemReadListener<String> {
private StepExecution stepExecution;
private static final String CURRENT_ID = "currentId";
@Override
public void beforeStep(final StepExecution stepExecution) {
this.stepExecution = stepExecution;
}
@Override
public ExitStatus afterStep(final StepExecution stepExecution) {
return null;
}
@Override
public void beforeRead() {
}
@Override
public void afterRead(final String item) {
String currentId = null;
if (stepExecution.getExecutionContext().containsKey(CURRENT_ID)) {
currentId = stepExecution.getExecutionContext().getString(CURRENT_ID);
} else {
String fileName = stepExecution.getExecutionContext().getString("fileName");
// ... create ID from FileName
currentId = fileName + "foo";
stepExecution.getExecutionContext().put(CURRENT_ID, currentId);
}
}
@Override
public void onReadError(final Exception ex) {
}
}
in the above example the current fileName is avavailable in the stepExecutionContext, it might be you have to pull it from jobParameters and extract the filename 在上面的示例中,当前文件名在stepExecutionContext中可用,可能是您必须从jobParameters中将其提取并提取文件名
String paramValue = stepExecution.getJobExecution().getJobParameters().getString("paramName");
// extract fileName from paramValue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.