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");

猜你喜欢

转载自blog.csdn.net/weixin_51751186/article/details/126822318