问题备忘: 将工程打包成jar包运行,就报java.io.FileNotFoundException: class path resource错误

当Spring Boot应用在IntelliJ IDEA中运行正常,但打包为jar后运行出现java.io.FileNotFoundException,原因是@Value注入的资源文件在jar中不再是独立文件。解决方法是将File参数替换为InputStream,使代码能在jar环境下正确读取资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在在使用@Value注入文件碰到如下问题:
工程在在IntelliJ IDEA开发环境里正常运行,但是一旦将工程打包成jar包运行,就报java.io.FileNotFoundException: class path resource错

代码如下:通过@Value将resource目录下test/billingconfig-file.xml目录注入到Resource上

@Value("classpath:test/billingconfig-file.xml")
private Resource resourceFile; // 注入计费点文件资源

JAXBContext context = JAXBContext.newInstance(BillingModelList.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
BillingModelList billingModelList = (BillingModelList) unmarshaller.unmarshal(resourceFile.getFile());

代码在IntelliJ IDEA开发环境里正常运行,但是一旦将工程打包成jar包运行,就提示如下错误:

java.io.FileNotFoundException: class path resource [test/billingconfig-file.xml] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/C:/Users/Administrator/Desktop/tmp/other/sp-bap-simulator-1.5.17.RELEASE.jar!/BOOT-INF/classes!/test/billingconfig-file.xml
	at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:215)
	at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:52)
	at im.yixin.spbap.logic.support.PayContext.init(PayContext.java:63)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:497)
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:366)
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:311)

原因是因为unmarshaller.unmarshal传入的参数是File,
在IntelliJ IDEA里运行时,billingconfig-file.xml是个独立的文件,可以被File访问到,
但是将工程打包成jar包运行,billingconfig-file.xml被封装到jar包中了,不是一个独立文件了,此时肯定无法使用File访问到。
了解了原因,我们可以将传递unmarshaller.unmarshal()方法的参数从File变成InputStream就可以了

将
unmarshaller.unmarshal(resourceFile.getFile());
修改为:
unmarshaller.unmarshal(resourceFile.getInputStream());

完整代码如下:

@Value("classpath:test/billingconfig-file.xml")
private Resource resourceFile; // 注入计费点文件资源

JAXBContext context = JAXBContext.newInstance(BillingModelList.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
BillingModelList billingModelList = (BillingModelList) unmarshaller.unmarshal(resourceFile.getInputStream())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值