java上下文类加载器,并在其中一个依赖项中加载资源时出现问题

beq87vna  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(176)

从jar文件中的静态类/方法加载属性文件时,我遇到了一个奇怪的问题。这个jar文件是spring引导应用程序的一部分。所以基本上是这样的结构

API-springboot.jar
|
|---- BOOT-INF/lib/my-other.jar
      |
      |----- app.properties
      |----- com/foo/bar/blah/Utils.class --> Static class loading app.properties

在这里 Utils.class 是各种静态实用程序方法的集合。 Util.class 使用静态方法加载 app.properties . 下面是代码 Utils ```
package com.foo.bar.blah;

public final class Utils {
private static final String PROPS_FILE = "app.properties";
private static final Properties props = loadProperties();

public static String doSomething(String str) {
    // ... some logic by reading props
    return "blah";
}

private static Properties loadProperties() {
    LOG.debug("Loading properties {}", PROPS_FILE);
    InputStream resourceAsStream = Thread.currentThread()
            .getContextClassLoader()
            .getResourceAsStream(PROPS_FILE);

    if (resourceAsStream == null) {
        throw new RuntimeException("Can't load the properties file " + PROPS_FILE);
    }

    Properties properties = new Properties();
    try {
        properties.load(new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8));
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }

    return properties;
}

}

现在当 `Utils.doSomething` 第一次调用, `loadProperties` 将被调用并加载 `app.properties` (在类路径的根目录下)
在本地(macos和openjdk 11.0.8)和我的 `test` env(rhel 7和openjdk 11.0.9)
在上部署时 `UAT` 环境,它找不到 `app.properties` 并引发方法中定义的异常

if (resourceAsStream == null) {
throw new RuntimeException("Can't load the properties file " + PROPS_FILE);
}

spring boot版本为 `v2.3.5.RELEASE` 下面是我到现在为止查过的
在 `UAT` ,我的jre与上的相同
test `UAT` 以及 `test` 具有通过ci/cd管道部署的相同版本的应用程序(jenkins/artifactory等)
在 `UAT` ,我提取了应用程序的spring boot jar文件,可以看到 `my-other.jar` 低于 `BOOT-INF/lib` 我核实过了 `my-other.jar` 有 `app.properties` 在根和 `Utils.class` 存在
我在一个 `UAT` 只需调用 `Utils.doSomething("blah")` 设置了正确的类路径,它可以加载 `app.properties` 显示预期结果。但是当从spring启动应用程序调用它时,问题就来了。
上的jre版本相同 `UAT` 以及 `test` spring启动应用程序使用的是正确的jre。

openjdk version "11.0.9" 2020-10-20 LTS
OpenJDK Runtime Environment 18.9 (build 11.0.9+11-LTS)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.9+11-LTS, mixed mode, sharing)

问题:是什么导致了这种行为?我遗漏了什么吗?花了3个小时都没有成功。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题