当我使用新的 Spring Batch 5 RC1 运行作业时,总是出现以下错误:
org.springframework.core.convert.ConverterNotFoundException:找不到能够从类型 [my.package.FileProvider] 转换为类型 [java.lang.String] 的转换器
所以,看来我需要提供一个GenericConverter
。但标准方法不起作用。
如果我通过以下方式注册它们:
@Configuration
public class ConverterRegistration implements WebMvcConfigurer {
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new FileConverter<>());
registry.addConverterFactory(new FileConverterFactory());
}
}
这不起作用。即使我扩展 DefaultBatchConfiguration
并使用 getConversionService().addConverter(new FileConverter())
等调用在 @PostConstruct
方法中设置转换器,
我的调试器显示转换器列表始终保持不变,异常来自于:GenericConversionService
。乔布斯似乎有自己的本地转换器列表。在断点处的第一次停止显示 GenericConversionService
有 129 个转换器,包括我的自定义转换器,而在稍后的停止处,当抛出异常时,它始终有 52 个转换器。
如何在那里添加转换器?
在 JobBuilder 上?
return new JobBuilder(JOB_IMPORT, jobRepository)
.incrementer(new RunIdIncrementer())
.start(infoImport)
.end()
.build();
在步骤构建器上?
new StepBuilder(getStepName(), jobRepository)
.<I, O>chunk(chunkSize, platformTransactionManager)
.listener(readListener)
.reader(reader)
.processor(processor)
.writer(writer)
很可能是作业参数,但是如何?
JobParameters jobParameters = new JobParametersBuilder()
.addJobParameter(FILE_PROVIDER,
new JobParameter<>(fileProvider, FileProvider.class))
.addString(INFO_FILE_NAME, fileInfo)
.toJobParameters();
jobLauncher.run(fileImportJob, jobParameters);
有人可以告诉我在哪里以及如何设置我的自定义GenericConverter
吗?
或者它是否需要某种JobParametersConverter
,但是:如何设置那个
(Spring Batch 5 RC1, Java Config 处的文档似乎不完整)?
最佳答案
网络转换器和批量转换器之间没有关系。您不应该期望 Spring Batch 将使用通过 WebMvcConfigurer
注册的转换器。
And even if I extend DefaultBatchConfiguration and set the converter in a @PostConstruct method with calls like getConversionService().addConverter(new FileConverter()),
这不起作用,因为 getConversionService()
始终返回 DefaultConversionService
的新实例。您需要覆盖 DefaultBatchConfiguration#getConversionService
并返回要用于作业参数的转换服务实例,包括所有转换器。这是一个典型的例子:
@Configuration
public class MyJobConfiguration extends DefaultBatchConfiguration {
@Bean
public Job job(JobRepository jobRepository) {
// define your job
return null;
}
@Override
protected ConfigurableConversionService getConversionService() {
DefaultConversionService conversionService = new DefaultConversionService();
// add converters to conversionService
return conversionService;
}
}
关于java - Spring Batch 参数转换不清楚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74195818/