【发布时间】:2017-11-23 23:22:36
【问题描述】:
我正在使用 Spring Boot 1.5 编写一个 Spring Batch 应用程序,以下是我的类:-
CustomMultiResourceItemReader.java
@StepScoped
@Component
public class CustomMultiResourceItemReader
extends MultiResourceItemReader<MyDTO> {
public MultiResourceXmlItemReader(
@NonNull final MyResourceAwareItemReader itemReader,
@NonNull final ApplicationContext ctx)
throws IOException {
setResources(
ctx.getResources(
String.format(
"file:%s/*.xml", "~/data"))); // gives me a Resource[] array fine
setDelegate(itemReader);
}
@PreDestroy
void destroy() {
close();
}
}
MyResourceAwareItemReader.java
@RequiredArgsConstructor
@StepScope
@Component
@Slf4j
public class MyResourceAwareItemReader
implements ResourceAwareItemReaderItemStream<MyDTO> {
private static final String RESOURCE_NAME_KEY = "RESOURCE_NAME_KEY";
@NonNull private final Unmarshaller unmarshaller; // JaxB Unmarshaller
private Resource resource;
@Override
public void setResource(Resource resource) {
this.resource = resource; // **gets called only once**
}
@Override
public MyDTO read() throws Exception {
final MyDTO dto = (MyDTO) unmarshaller.unmarshal(resource.getFile()); // Standard JaxB unmarshalling.
return dto;
}
@Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
if (executionContext.containsKey(RESOURCE_NAME_KEY)) {
} else if (resource != null) {
executionContext.put(RESOURCE_NAME_KEY, resource.getFilename());
}
}
@Override
public void update(ExecutionContext executionContext) throws ItemStreamException {
if (resource != null) executionContext.put(RESOURCE_NAME_KEY, resource.getFilename());
}
@Override
public void close() throws ItemStreamException {}
}
问题是delegate阅读器(MyResourceAwareItemReader.java)中的setResource方法在开始时只被调用一次;虽然 read 方法被多次调用,结果我多次读取同一个项目,而不是按预期读取下一个项目。
我也浏览了MultiResouceItemReader in Spring Batch的源代码,好像是委托类的read方法应该是在读取每一项后返回null,我可以清楚地看到我的代码似乎没有这样做。
我有点迷失了如何使这项工作。非常感谢任何帮助
【问题讨论】:
标签: spring spring-boot spring-batch batch-processing