我有一个弹出批处理作业(在xml中定义),它生成csv导出。 在FlatFileItemWriter bean内部我正在设置资源,其中设置了文件名。
<bean id="customDataFileWriter" class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
<property name="resource" value="file:/tmp/export/custom-export.csv"/>
...
现在我需要设置这个文件名,考虑到某个逻辑,所以我需要从某个java类设置文件名。有什么想法吗?
答案 0 :(得分:1)
使用spring批处理的不同构建器类(作业构建器,步骤构建器等)。看看https://blog.codecentric.de/en/2013/06/spring-batch-2-2-javaconfig-part-1-a-comparison-to-xml/以获得一个想法。
答案 1 :(得分:1)
您可以实现自己的FlatFileItemWriter
来覆盖方法setResource
并添加自己的逻辑来重命名文件。
以下是一个示例实现:
@Override
public void setResource(Resource resource) {
if (resource instanceof ClassPathResource) {
// Convert resource
ClassPathResource res = (ClassPathResource) resource;
try {
String path = res.getPath();
// Do something to "path" here
File file = new File(path);
// Check for permissions to write
if (file.canWrite() || file.createNewFile()) {
file.delete();
// Call parent setter with new resource
super.setResource(new FileSystemResource(file.getAbsolutePath()));
return;
}
} catch (IOException e) {
// File could not be read/written
}
}
// If something went wrong or resource was delegated to MultiResourceItemWriter,
// call parent setter with default resource
super.setResource(resource);
}
如果您的逻辑可以在作业启动之前应用,则使用jobParameters
存在另一种可能性。请参阅Spring Batch Documentation的5.4 Late Binding。
示例:
<bean id="flatFileItemReader" scope="step" class="org.springframework.batch.item.file.FlatFileItemReader">
<property name="resource" value="#{jobParameters['input.file.name']}" />
</bean>
您还可以将MultiResourceItemWriter
与自定义ResourceSuffixCreator
一起使用。这将允许您使用通用文件名模式创建1到n个文件。
以下是自定义getSuffix
的方法ResourceSuffixCreator
的示例:
@Override
public String getSuffix(int index) {
// Your logic
if (true)
return "XXX" + index;
else
return "";
}