Spring Boot资源文件读取报错:RSA非对称加密应用空指针异常
解决Spring Boot中非对称加密工具类的NullPointerException问题
我来帮你拆解下这个空指针异常的核心原因,以及一步步修复的方案:
问题根源分析
1. 错误的资源读取方式
你在getPrivate方法里用new File(filename).toPath()读取classpath资源,这在Spring Boot打包成jar包后完全行不通——jar里的资源是包内的条目,不是磁盘上的独立文件,直接用File会找不到路径,导致抛出异常;而如果filename本身是无效值(比如res.getFilename()只返回文件名而非完整路径),就会触发空指针。
2. 手动实例化Spring管理的Bean
在encryptWithKey里你手动new Loader(),这会创建一个脱离Spring容器的实例,虽然这里你没用到这个实例的resourceLoader,但这种做法违背了Spring的依赖注入逻辑,后续如果扩展代码很容易出现其他注入依赖的空指针。
3. res.getFilename()的误用
Resource.getFilename()返回的仅仅是资源的文件名(比如privateKey),不是完整的classpath路径,所以传给getPrivate方法后,new File(filename)根本找不到对应的文件,这是直接触发空指针或文件找不到异常的原因。
完整修复代码
@Component public class Loader { private Cipher cipher; private PrivateKey privateKey; public String enText; @Autowired private ResourceLoader resourceLoader; // 配置化路径,可在application.properties里设置asymetric.private.key-store的值 @Value("${asymetric.private.key-store:classpath:KeyPair/privateKey}") private String privateKeyPath; // Spring管理的Bean建议使用空构造器,避免构造器抛异常导致Bean初始化失败 public Loader() {} // 用@PostConstruct在Bean初始化完成后初始化Cipher @PostConstruct public void initCipher() throws NoSuchAlgorithmException, NoSuchPaddingException { this.cipher = Cipher.getInstance("RSA"); } public String encryptText(String msg, PrivateKey key) throws UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException { this.cipher.init(Cipher.ENCRYPT_MODE, key); return Base64.encodeBase64String(cipher.doFinal(msg.getBytes("UTF-8"))); } // 改为通过Resource的InputStream读取资源,兼容jar包环境 public PrivateKey getPrivate(Resource resource) throws Exception { try (InputStream inputStream = resource.getInputStream()) { byte[] keyBytes = inputStream.readAllBytes(); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(spec); } } public String encryptWithKey(String msg) throws Exception { // 通过resourceLoader获取完整的资源对象 Resource privateKeyResource = resourceLoader.getResource(privateKeyPath); // 提前检查资源是否存在,抛出明确的异常便于调试 if (!privateKeyResource.exists()) { throw new FileNotFoundException("Private key resource not found at: " + privateKeyPath); } // 使用当前Bean的方法,不要手动new实例 privateKey = getPrivate(privateKeyResource); return encryptText(msg, privateKey); } }
关键修复点说明
- 兼容jar包的资源读取:用
Resource.getInputStream()替代Files.readAllBytes(new File(...)),无论项目是IDE运行还是打包成jar,都能正确读取classpath内的资源。 - 避免手动实例化Bean:直接使用Spring注入的当前Bean的方法,确保所有依赖(比如
resourceLoader)都能正常注入。 - 安全的Bean初始化:把Cipher的初始化移到
@PostConstruct方法中,避免构造器抛出异常导致Spring无法创建Bean。 - 配置化路径:通过
@Value实现密钥路径的可配置,同时设置默认值,提升代码灵活性。 - 异常提前检测:添加资源存在性检查,抛出明确的
FileNotFoundException,比空指针更容易定位问题。
内容的提问来源于stack exchange,提问作者Kunle Ajiboye
相关产品推荐
相关产品推荐

