在spring jar 中加载文件

2018-07-02  本文已影响0人  桃子_3e05

今天写一个spring boot 的demo,需要通过加载配置文件,调用第三方服务,配置文件存储的是第三方服务的地址和认证信息。开始通过 new ClassPathResource("config.json").getFile() 获取文件,在IntelliJ IDEA 调用是ok的,但是当打包成jar调用会抛出如下异常:

{

    "timestamp": "2018-07-02T09:13:22.829+0000",

    "status": 500,

    "error": "Internal Server Error",

    "message": "class path resource [config.json] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/E:/demo-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/config.json",

    "path": "/compare"

}

查询资料后发现,jar包是一个是文件包,类似于zip包。所以jar包中的配置文件不存在于操作系统的文件树中,要使用jar包中的文件,必须要用流的方式读取包中的文件。后面修改成用流的方式读取文件new ClassPathResource("config.json").getInputStream(),在spring jar包中成功加载到了配置文件。

上一篇下一篇

猜你喜欢

热点阅读