gpt4 book ai didi

java - 来自另一个类的 Spring Batch MultiResourceItemReader 资源引用

转载 作者:行者123 更新时间:2023-11-30 02:16:02 24 4
gpt4 key购买 nike

除了从 JobParameters 获取值或使用 Value 标签之外,还有其他方法可以自定义 MultiResourceItemReader 资源吗?我尝试了以下方法,但没有成功。

<bean id="ItemReader" class="org.springframework.batch.item.file.MultiResourceItemReader" scope="step">
<property name="resources" ref="fileResources" />
<property name="delegate" ref="flatFileItemReader" />
</bean>

<bean id="fileResources" class="com.app.batch.fileloader.file.FileResources" />

<bean id="flatFileItemReader" class="com.app.batch.fileloader.file.MyFlatFileItemReader">
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<property name="lineTokenizer">
<bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="delimiter" value="," />
</bean>
</property>
<property name="fieldSetMapper">
<bean class="com.app.batch.fileloader.file.MyFileFieldSetMapper" />
</property>
</bean>
</property>
</bean>

在 FileResources Java 类中,我像这样扩展了 MultiResourceItemReader

public class FileResources extends MultiResourceItemReader<FileDTO>{

@Override
public void setResources(Resource[] resources){
ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
try{
resources = patternResolver.getResources("file:" + properties.getPath() + "/*.csv");
}
catch(IOException ex){
LOG.error("The resources must not be null");
}

super.setResources(resources);
}

我做错了什么,有人可以告诉我吗?谢谢!

最佳答案

使用FactoryBean。创建一个返回 Resource [] 的实现,并将其注入(inject)到您的 MultiResourceItemReader 中。 Spring 将调用工厂 bean 并使用输出来填充依赖项。

一个例子看起来像这样:

<bean id="ItemReader" class="org.springframework.batch.item.file.MultiResourceItemReader" scope="step">
<property name="resources" ref="fileResources" />
<property name="delegate" ref="flatFileItemReader" />
</bean>

<bean id="fileResources" class="com.app.batch.fileloader.file.ResourcesFactoryBean" />

通过上述配置,您将使用以下 FactoryBean 实现:

public class ResourcesFactoryBean implements FactoryBean<Resource[]>{

@Override
public Resource[] getObject() {
ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
try{
resources = patternResolver.getResources("file:" + properties.getPath() + "/*.csv");
}
catch(IOException ex){
LOG.error("The resources must not be null");
}

return resources;
}
...

您可以在此处的文档中阅读有关 Spring 的 FactoryBean 接口(interface)的更多信息:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/FactoryBean.html

这里:https://docs.spring.io/spring/docs/5.0.3.RELEASE/spring-framework-reference/core.html#beans-factory-extension-factorybean

关于java - 来自另一个类的 Spring Batch MultiResourceItemReader 资源引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48407408/

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