不小心入坑,不止我一个人遇到。还有其他老哥:
https://blog.youkuaiyun.com/baQiWangZhengLiang/article/details/84568846
场景:
项目需要用一个定制化的文件,写成了.json文件放在了resources文件夹里,代码大概如下:
final File file = ResourceUtils.getFile("classpath:type.json");
final String fileContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {};
现象:
本地调试很正常,镜像打包正常,测试环境部署时一直重启。
原因:
开始时怀疑是gradle配置问题,.json没有打包进去,后来证明并不是。
查了一圈发现是这个问题:getFile()不能嵌套在jar文件中。
划重点。
解决方案:
Resource resource = new ClassPathResource("type.json");
final String content = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8);
TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {};