在JAR中加载属性文件?

我遇到麻烦时,我的Web应用程序所依赖的一个jar子试图从jar中加载属性文件。 这是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的junittesting中运行这个代码时,它执行得很好。 当使用Maven将项目构build到jar中,并将其作为依赖项包含在webb应用程序中时,将无法find属性文件。 我知道属性文件是在依赖jar的基础目录,我不知道如何解决这个问题。

请帮忙!

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

它在Eclipse中工作,因为启动一个应用程序时,系统类加载器被configuration为您的jar作为其类path的一部分。 (例如,java -jar my.jar会将my.jar加载到系统类加载器中。)Web应用程序并不是这种情况 – 应用程序服务器使用复杂的类加载将应用程序彼此和应用程序服务器的内部隔离。 例如,请参阅tomcat classloader的使用方法以及使用的类加载器层次结构图。

编辑:通常,您将调用getClass()。getResourceAsStream()来检索类path中的资源,但是当您在静态初始化程序中获取资源时,您将需要明确地指定您要在类加载器中的类加载来自。 最简单的方法是使用包含静态初始化器的类,例如

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

为了logging,这是logging在如何将资源添加到我的JAR? (unit testing说明,但同样适用于“常规”资源):

要将资源添加到unit testing的类path中,除了将资源放置在${basedir}/src/test/resources的目录之外,您将遵循与将资源添加到JAR的模式相同的模式。 在这一点上,你将有一个项目目录结构,如下所示:

 my-app |-- pom.xml `-- src |-- main | |-- java | | `-- com | | `-- mycompany | | `-- app | | `-- App.java | `-- resources | `-- META-INF | |-- application.properties `-- test |-- java | `-- com | `-- mycompany | `-- app | `-- AppTest.java `-- resources `-- test.properties 

在unit testing中,您可以使用如下所示的简单代码片段来访问testing所需的资源:

 ... // Retrieve resource InputStream is = getClass().getResourceAsStream("/test.properties" ); // Do something with the resource ...