
在开发阶段,我们可能习惯于使用classloader.getsystemresource("path/to/resource").touri()结合files.readallbytes(paths.get(...))来读取src/main/resources目录下的文件。这种方式在ide中直接运行时通常表现良好,因为此时资源文件以独立文件的形式存在于文件系统路径上。
然而,当Spring Boot应用被打包成可执行的JAR文件后,resources目录下的文件不再是独立的文件,而是被嵌入到JAR包内部,成为JAR文件的一部分。此时,尝试将JAR包内部的资源转换为文件系统路径(toURI()后通常会得到一个jar:协议的URI,而非file:协议),然后使用Paths.get()去读取,就会导致FileNotFoundException或其他IO错误,因为Paths.get()无法直接处理JAR内部的URI。
例如,原始问题中尝试的以下代码:
String Key = new String(Files.readAllBytes(Paths.get(ClassLoader.getSystemResource("key/private.pem").toURI())));在JAR包环境中就会失效,因为它试图将一个JAR内部的资源映射到一个文件系统路径,这在物理上是不存在的。
Spring Framework 为解决此类问题提供了强大的抽象——org.springframework.core.io.Resource接口及其各种实现类。其中,ClassPathResource是处理类路径下资源的理想选择。
ClassPathResource能够识别并加载位于类路径上的任何资源,无论是独立的类文件、外部JAR包中的资源,还是当前应用JAR包内部的资源。它通过getInputStream()方法提供对资源内容的访问,而无需关心资源是位于文件系统上还是JAR包内部。
为了方便地读取类路径下的资源文件内容,我们可以封装一个通用的工具方法。以下是一个推荐的实现,它利用了ClassPathResource和Spring的FileCopyUtils:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;
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);
/**
* 从类路径加载资源文件内容。
* 该方法适用于Spring Boot应用打包成JAR后,依然能够正确读取resources目录下的文件。
*
* @param resourcePath 资源在类路径下的相对路径,例如 "key/private.pem" 或 "config/application.yml"。
* @return 资源文件的内容字符串,如果加载失败则返回null。
* @throws NullPointerException 如果resourcePath为null。
*/
public static String getResourceFileContent(String resourcePath) {
Objects.requireNonNull(resourcePath, "Resource path cannot be null.");
// 创建ClassPathResource实例,它会自动查找类路径下的资源
ClassPathResource resource = new ClassPathResource(resourcePath);
try {
// 使用FileCopyUtils将资源输入流的内容复制到字节数组
// FileCopyUtils.copyToByteArray 会自动关闭输入流
byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
// 将字节数组转换为字符串,推荐指定字符集以避免乱码
return new String(bytes, StandardCharsets.UTF_8);
} catch (IOException ex) {
// 记录错误日志,包含资源路径和异常信息
log.error("Failed to load resource file: {}", resourcePath, ex);
return null; // 或者抛出自定义异常
}
}
}假设你的公钥和私钥文件分别位于src/main/resources/key/public.pem和src/main/resources/key/private.pem。你可以这样使用上述工具方法来获取它们的内容:
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 {
private PublicKey getPublicKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
// 使用ResourceLoaderUtil获取公钥文件内容
String keyContent = ResourceLoaderUtil.getResourceFileContent("key/public.pem");
if (keyContent == null) {
throw new RuntimeException("Failed to load public key resource.");
}
String key = keyContent.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);
}
private PrivateKey getPrivateKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
// 使用ResourceLoaderUtil获取私钥文件内容
String keyContent = ResourceLoaderUtil.getResourceFileContent("key/private.pem");
if (keyContent == null) {
throw new RuntimeException("Failed to load private key resource.");
}
String key = keyContent.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);
}
public static void main(String[] args) {
KeyLoader loader = new KeyLoader();
try {
PublicKey publicKey = loader.getPublicKey();
PrivateKey privateKey = loader.getPrivateKey();
System.out.println("Public Key loaded: " + (publicKey != null));
System.out.println("Private Key loaded: " + (privateKey != null));
// 进一步使用publicKey和privateKey
} catch (Exception e) {
System.err.println("Error loading keys: " + e.getMessage());
e.printStackTrace();
}
}
}通过采用Spring Framework提供的ClassPathResource和FileCopyUtils,我们可以优雅且健壮地解决Spring Boot应用在JAR包环境中读取resources目录下文件的问题。这种方法不仅保证了开发和生产环境的一致性,还通过Spring的抽象层提供了更高级别的资源管理能力,是Spring Boot项目中加载类路径资源的推荐方式。它避免了底层文件系统路径的复杂性,使资源访问变得简单可靠。
以上就是Spring Boot 应用中安全获取资源文件:解决JAR打包后的兼容性问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号