在 JAR 中加载属性文件? [英] Load properties file in JAR?

查看:21
本文介绍了在 JAR 中加载属性文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的 Web 应用程序依赖的其中一个 jar 尝试从 jar 中加载属性文件时,我遇到了问题.这是jar中的代码.

I'm having trouble when one of the jars that my web app depends on tries to load a properties file from within the jar. Here is the code in the jar.

static
{
    Properties props = new Properties();
    try 
    {
        props.load(ClassLoader.getSystemResourceAsStream("someProps.properties"));
    } catch (IOException e) 
    {
        e.printStackTrace();
    }
    someProperty = props.getProperty("someKey");
}

属性文件在我 Maven 项目的src/main/resources"目录中.当我从 Eclipse 中的 junit 测试运行此代码时,它执行得很好.当项目使用 Maven 构建到 jar 中,并作为依赖项包含在我的 Web 应用程序中时,它无法找到属性文件.我知道属性文件位于依赖的 jar 的基目录中,我不知道如何解决这个问题.

The properties file is in my "src/main/resources" directory of the Maven project. When I run this code from my junit test in Eclipse, it executes just fine. When the project is built with Maven into a jar, and included as a dependency in my web app, it fails to locate the properties file. I know that the properties file is at the base directory of the depended on jar, I don't know how to fix this.

推荐答案

问题在于您使用的是 getSystemResourceAsStream.只需使用 getResourceAsStream.系统资源从系统类加载器加载,这几乎肯定不是你的 jar 作为 webapp 运行时加载到的类加载器.

The problem is that you are using getSystemResourceAsStream. Use simply getResourceAsStream. System resources load from the system classloader, which is almost certainly not the class loader that your jar is loaded into when run as a webapp.

它在 Eclipse 中有效,因为在启动应用程序时,系统类加载器配置了您的 jar 作为其类路径的一部分.(例如,java -jar my.jar 将在系统类加载器中加载 my.jar.)Web 应用程序不是这种情况——应用程序服务器使用复杂的类加载来将 Web 应用程序彼此隔离,并与应用程序服务器的内部隔离.例如,请参阅 tomcat 类加载器操作方法,以及使用的类加载器层次结构图.

It works in Eclipse because when launching an application, the system classloader is configured with your jar as part of its classpath. (E.g. java -jar my.jar will load my.jar in the system class loader.) This is not the case with web applications - application servers use complex class loading to isolate webapplications from each other and from the internals of the application server. For example, see the tomcat classloader how-to, and the diagram of the classloader hierarchy used.

通常,您会调用 getClass().getResourceAsStream() 来检索类路径中的资源,但是当您在静态初始化程序中获取资源时,您需要显式命名您要从中加载的类加载器中的类.最简单的方法是使用包含静态初始化器的类,例如

Normally, you would call getClass().getResourceAsStream() to retrieve a resource in the classpath, but as you are fetching the resource in a static initializer, you will need to explicitly name a class that is in the classloader you want to load from. The simplest approach is to use the class containing the static initializer, e.g.

[public] class MyClass {
  static
  {
    ...
    props.load(MyClass.class.getResourceAsStream("/someProps.properties"));
  }
}

这篇关于在 JAR 中加载属性文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆