Spring Boot替换MultipartFile为InputStream后Repository报空指针如何解决
问题排查与解决方案
核心问题定位
- Spring不支持直接@Autowired注入静态成员变量:你将所有DAO层接口都声明为static修饰,@Autowired无法为静态属性完成依赖注入,导致这几个interface实例全部为null,调用save方法时就会触发空指针异常,这是本次问题的根因。
- 误用静态方法设计:Spring管理的Bean默认是单例,不需要把业务方法声明为static,静态方法脱离了Spring的Bean管理上下文,也会直接导致注入失效。
- 额外边界风险:InputStream只能被读取一次,如果调用uploadFile方法之前流已经被消费、关闭,ParseHelper解析返回的List可能为null,遍历时也会触发空指针。
修复步骤
- 移除FileService里所有不必要的static修饰,恢复为普通Spring Bean写法,同时增加非空校验避免边界异常:
@Service public class FileService { @Autowired private Interface_freight_index interface_freight_index; @Autowired private Interface_freight_chargecodes interface_freight_chargecodes; @Autowired private Interface_billing_invoice_items interface_billing_invoice_items; @Autowired private Interface_billing_invoice_header interface_billing_invoice_header; public void save(InputStream file, boolean isCsv, boolean isXlsx) { List<Object> freightIndex = ParseHelper.FileParser(file, isCsv, isXlsx); // 提前判断列表非空再遍历 if (freightIndex == null || freightIndex.isEmpty()) { return; } try { for (Object row : freightIndex) { if (row instanceof freight_index) { interface_freight_index.save((freight_index) row); } else if (row instanceof freight_chargecodes) { interface_freight_chargecodes.save((freight_chargecodes) row); } else if (row instanceof billing_invoice_items) { interface_billing_invoice_items.save((billing_invoice_items) row); } else if (row instanceof billing_invoice_header) { interface_billing_invoice_header.save((billing_invoice_header) row); } } } catch (Exception e) { e.printStackTrace(); } } }
- 修正FileController写法,去掉静态方法,通过注入方式调用FileService:
@CrossOrigin("http://localhost:8080") @Controller public class FileController { @Autowired private FileService fileService; public void uploadFile(InputStream file, boolean isCsv, boolean isXlsx) { try { fileService.save(file, isCsv, isXlsx); } catch (Exception e) { e.printStackTrace(); } } }
- 调用uploadFile前确认传入的InputStream没有被提前读取、关闭,确保流处于可用状态。
内容的提问来源于stack exchange,提问作者KangDo
相关产品推荐
相关产品推荐

