You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Batch批处理作业报错:Input resource must exist(严格模式)

Spring Batch作业报错「Input resource must exist (reader is in 'strict' mode)」解决建议

问题描述

运行一个读取CSV文件、格式化对象并写入另一个文件的Spring Batch简单批处理作业时,出现**「Input resource must exist (reader is in 'strict' mode)」**错误。尽管输入和输出文件均存在于Spring Boot项目的resource目录中(该示例来自《Spring Batch权威指南》),作业仍执行失败。

构建命令

$ mvn clean package

运行命令

$ java -jar target/chapter09_format_customer_address-0.0.1-SNAPSHOT.jar customerFile=/Users/psingh6/Documents/learn/springBatch/chapter09_format_customer_address/src/main/resources/data.csv outputFile=/Users/psingh6/Documents/learn/springBatch/chapter09_format_customer_address/src/main/resources/formattedCustomerFile.txt

核心错误日志

Caused by: java.lang.IllegalStateException: Input resource must exist (reader is in 'strict' mode): ServletContext resource [/Users/psingh6/Documents/learn/springBatch/chapter09_format_customer_address/src/main/resources/data.csv]

相关配置:pom.xml、application.properties及批处理作业配置类FormattedTextFileJob.java(代码详见原文)


问题原因

错误日志显示系统把你传入的绝对路径当成了ServletContext资源(即Web应用内部的相对路径),而非操作系统的绝对文件路径。这说明文件读取器(大概率是FlatFileItemReader)配置时,使用了基于ServletContext的资源加载方式,而非文件系统资源加载逻辑。

解决步骤

1. 调整文件读取器的资源配置

在FormattedTextFileJob.java中,确保文件读取器使用FileSystemResource来加载系统绝对路径的文件,替换默认的资源加载方式:

@Value("${customerFile}")
private String customerFilePath;

@Bean
public FlatFileItemReader<Customer> customerItemReader() {
    FlatFileItemReader<Customer> reader = new FlatFileItemReader<>();
    // 明确使用FileSystemResource加载绝对路径文件
    reader.setResource(new FileSystemResource(customerFilePath));
    // 行映射器、分隔符等其他原有配置保持不变
    return reader;
}

2. 可选:使用类路径资源访问JAR内文件

如果希望直接读取打包后JAR内部的resource文件,不能用绝对路径,需改为类路径方式访问:

  • 修改运行命令:
    $ java -jar target/chapter09_format_customer_address-0.0.1-SNAPSHOT.jar customerFile=classpath:data.csv outputFile=file:/Users/psingh6/Documents/learn/springBatch/chapter09_format_customer_address/src/main/resources/formattedCustomerFile.txt
    
  • 同步调整读取器配置:
    reader.setResource(new ClassPathResource(customerFilePath));
    

注意:输出文件无法写入JAR内部,必须用file:前缀指定系统绝对路径。

3. 临时排查:关闭严格模式(不建议长期使用)

若确认路径无误但仍报错,可临时关闭读取器的严格模式辅助排查:

reader.setStrict(false);

内容的提问来源于stack exchange,提问作者Prashant Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:24:26