
在 spring boot 项目开发中,我们经常需要从 src/main/resources 目录下读取配置文件、模板文件、证书等各类资源。常见的做法是使用 classloader.getsystemresource() 结合 java.nio.file.paths 来获取文件路径并读取内容。然而,当 spring boot 应用被打包成可执行的 jar 文件后,这种基于文件系统路径的方式往往会失效。这是因为 jar 文件内部的资源并非传统意义上的文件系统路径,而是以压缩包的形式存在。直接使用 paths.get(uri) 尝试访问 jar 内部资源时,会因为文件系统提供者无法处理 jar 内部路径而抛出异常。
为了解决这个问题,Spring Framework 提供了一套强大且灵活的资源加载机制,其中 org.springframework.core.io.ClassPathResource 是处理 Classpath 资源的理想选择。ClassPathResource 能够抽象底层资源的物理位置,无论是文件系统中的独立文件,还是 JAR 包内部的条目,它都能以统一的方式进行访问。
ClassPathResource 能够从 Classpath 中定位并加载资源。它内部处理了资源在文件系统或 JAR 包中的差异,提供了统一的 getInputStream() 方法来获取资源的输入流。结合 Spring 的 org.springframework.util.FileCopyUtils 工具类,可以方便地将输入流内容读取为字节数组或字符串。
以下是一个通用的工具方法,用于安全地读取 Classpath 资源文件的内容:
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
public class ResourceLoaderUtil {
private static final Logger log = LoggerFactory.getLogger(ResourceLoaderUtil.class);
/**
* 从 Classpath 中读取指定资源文件的内容。
*
* @param resourcePath 资源在 Classpath 中的路径,例如 "key/private.pem" 或 "application.properties"。
* @return 资源文件的内容字符串,如果读取失败则返回 null。
* @throws NullPointerException 如果 resourcePath 为 null。
*/
public static String getResourceFileContent(String resourcePath) {
Objects.requireNonNull(resourcePath, "Resource path cannot be null.");
// 创建 ClassPathResource 实例,它会从 Classpath 中查找资源
ClassPathResource resource = new ClassPathResource(resourcePath);
try {
// 使用 FileCopyUtils 将资源的 InputStream 内容复制到字节数组
byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
// 将字节数组转换为字符串,通常使用 UTF-8 编码
return new String(bytes, StandardCharsets.UTF_8);
} catch (IOException ex) {
// 记录错误日志,说明资源文件读取失败的原因
log.error("Failed to read resource file: {}", resourcePath, ex);
return null; // 或者抛出自定义异常
}
}
}假设我们需要加载 src/main/resources/key/private.pem 和 src/main/resources/key/public.pem 文件来构建 PrivateKey 和 PublicKey 对象。我们可以将上述 getResourceFileContent 方法集成到原有的逻辑中:
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class KeyLoader {
/**
* 获取公钥内容。
* @return 公钥字符串。
*/
private String getPublicKeyContent() {
// 使用我们定义的工具方法读取公钥文件
return ResourceLoaderUtil.getResourceFileContent("key/public.pem");
}
/**
* 获取私钥内容。
* @return 私钥字符串。
*/
private String getPrivateKeyContent() {
// 使用我们定义的工具方法读取私钥文件
return ResourceLoaderUtil.getResourceFileContent("key/private.pem");
}
/**
* 根据内容构建 PublicKey 对象。
* @return PublicKey 实例。
* @throws NoSuchAlgorithmException 如果算法不支持。
* @throws InvalidKeySpecException 如果密钥规范无效。
*/
public PublicKey getPublicKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
String key = getPublicKeyContent();
if (key == null) {
throw new IOException("Public key content is null. Resource not found or failed to read.");
}
key = key.replaceAll("\n", "")
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(keySpec);
}
/**
* 根据内容构建 PrivateKey 对象。
* @return PrivateKey 实例。
* @throws NoSuchAlgorithmException 如果算法不支持。
* @throws InvalidKeySpecException 如果密钥规范无效。
*/
public PrivateKey getPrivateKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
String key = getPrivateKeyContent();
if (key == null) {
throw new IOException("Private key content is null. Resource not found or failed to read.");
}
key = key.replaceAll("\n", "")
.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(keySpec);
}
}通过采用 Spring Framework 提供的 ClassPathResource 等工具,我们可以确保在 Spring Boot 应用中以统一、健壮的方式加载 Classpath 资源,无论应用是以开发模式运行还是打包成 JAR 部署,都能保持良好的兼容性和稳定性。
以上就是Spring Boot 应用中安全可靠地读取 Classpath 资源文件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号