微信退款SpringBoot读取resource下的证书

近期做了一个微信支付退款接口,需要证书双向验证,测试的时候证书暂时放在resource下,上图

起初MyConfig中我是这样,在本机IDE中运行没有问题

import org.springframework.util.ResourceUtils; 
 
public MyConfig() throws Exception {
     
        File file = (ResourceUtils.getFile("classpath:config/apiclient_cert.p12"));
        InputStream certStream = new FileInputStream(file);
        this.certData = new byte[(int) file.length()];
        certStream.read(this.certData);
        certStream.close();
    }

但到Linux服务器的docker中运行就IO异常了,查阅资料可能原因是内嵌web容器访问的是jar包,

解决方法1:

import org.apache.commons.io.IOUtils;
 
public InputStream getCertStream() {
     
        try {
     
            InputStream certStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config/apiclient_cert.p12");
            this.certData = IOUtils.toByteArray(certStream);
            certStream.close();
        } catch (Exception e) {
     
            e.printStackTrace();
        }
        ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }

解决方法2:

import org.springframework.core.io.ClassPathResource;
 
public InputStream getCertStream() {
     
          try {
     
            ClassPathResource classPathResource = new ClassPathResource("config/apiclient_cert.p12");
            //获取文件流
            InputStream certStream = classPathResource.getInputStream();
            this.certData = IOUtils.toByteArray(certStream);
            certStream.read(this.certData);
            certStream.close();
        } catch (IOException e) {
     
            e.printStackTrace();
        }
   }

你可能感兴趣的:(springboot,java)