問題備忘: 將工程打包成jar包運行,就報java.io.FileNotFoundException: class path resource錯誤

最近在在使用@Value注入文件碰到以下問題: 工程在在IntelliJ IDEA開發環境里正常運行,可是一旦將工程打包成jar包運行,就報java.io.FileNotFoundException: class path resource錯java

代碼以下:經過@Value將resource目錄下test/billingconfig-file.xml目錄注入到Resource上spring

@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包運行,就提示以下錯誤:bash

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就能夠了ide

將
unmarshaller.unmarshal(resourceFile.getFile());
修改成:
unmarshaller.unmarshal(resourceFile.getInputStream());
複製代碼

完整代碼以下:ui

@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())
複製代碼
相關文章
相關標籤/搜索