springboot构建为jar后(生产环境),如何也能访问resouore下的文件


前言

本篇博客参考自
https://blog.csdn.net/qq_43684985/article/details/115341746

最近在学习微信支付
读取用户私钥时在本地测试可以读取成功
但打成jar包后读取失败

原因

springboot项目在打成jar包后 是无法访问其中文件的
类加载器可以读取jar包中编译后的class文件
所以要把代码改造成类加载器的方式获取

改造(在生产和开发环境下都能运行)

/**
     * 获取商户的私钥文件
     * @param filename
     * @return
     */
    public PrivateKey getPrivateKey(String filename){

        try {

            //改造后代码  打包成jar后仍能正常访问
            //ClassPathResource classPathResource = new ClassPathResource("apiclient_key.pem");
            ClassPathResource classPathResource = new ClassPathResource(filename);
            InputStream inputStream = classPathResource.getInputStream();
            //通过导入的SDK 和 商户的数字证书路径filename 获得 PrivateKey 并且返回
            return PemUtil.loadPrivateKey(inputStream);

//            源代码 没有使用类加载器的方式 打包成jar后报错
//            //通过导入的SDK 和 商户的数字证书路径filename 获得 PrivateKey 并且返回
//            return PemUtil.loadPrivateKey(new FileInputStream(filename));


        } catch (FileNotFoundException e )  {
            throw new RuntimeException("私钥文件不存在", e);
        } catch (IOException e) {
            throw  new RuntimeException("私钥文件不存在",e);
        }
    }

总结几种方式

第一种:

ClassPathResource classPathResource = new ClassPathResource("excleTemplate/test.xlsx");
InputStream inputStream = classPathResource.getInputStream();

第二种:

InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("excleTemplate/test.xlsx");

第三种:

InputStream inputStream  = this.getClass().getResourceAsStream("/excleTemplate/test.xlsx");
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qwecxzz

鸡腿

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值