从WAR模块中嵌入EAR / lib jar中的访问属性文件

时间:2017-12-12 19:53:15

标签: java-ee classloader wildfly-10

我有一个直接的J2EE应用程序打包为EAR并部署到在RHEL上运行的Wildfly 10.1.0。 EAR包含EJB模块,WAR模块和公共库模块(Commons-1.0-SNAPSHOT.jar),它驻留在EAR的/ lib文件夹中以及其他依赖项。在Commons-1.0-SNAPSHOT.jar的根目录中,我有一个属性文件(util.properties),它由一个实用程序/帮助程序类(即cc.iapps.sprd.commons.Utility)读取,它们打包在同一个jar中。   WAR模块使用Utility类,但是在初始化类时,属性文件无法加载,并显示以下错误:

找不到属性文件:java.io.FileNotFoundException:/content/SpreadServices-ear-1.0-SNAPSHOT.ear/lib/Commons-1.0-SNAPSHOT.jar/util.properties(没有这样的文件或目录)

Utility类确实被加载了,所以我知道Commons-1.0-SNAPSHOT.jar在WAR的类路径中。另外,我已经验证了属性文件位于jar文件的根目录下,并且jar文件位于EAR的/ lib文件夹中。

我用来加载属性文件的代码如下:

ClassLoader classLoader = this.getClass().getClassLoader();
File file = new File(classLoader.getResource("util.properties").getFile());
        Properties props = new Properties();
        props.load(new FileInputStream(file));

奇怪的是,当我在开发机器上从Eclipse本地部署到Wildfly 10.1时,应用程序运行正常。我怀疑这是因为本地版本被部署为引用我的开发文件结构的爆炸EAR。

2 个答案:

答案 0 :(得分:2)

您通常不应该尝试将类加载器资源作为java.io.File对象读取。它们不存在于文件系统中,除非您碰巧在爆炸部署中执行。

您提供的解决方案可以折叠为:

ClassLoader classLoader = this.getClass().getClassLoader();
Properties props = new Properties();
props.load(classLoader.getResourceAsStream("/util.properties"));

或更正确:

ClassLoader classLoader = this.getClass().getClassLoader();
try (InputStream utilsInput = classLoader.getResourceAsStream("/util.properties")) {
    Properties props = new Properties();
    props.load(utilsInput);
    ...
}

进行适当的资源管理。

答案 1 :(得分:0)

资源名称似乎必须以' /'为前缀,因此将代码更改为以下内容可以解决它:

ClassLoader classLoader = this.getClass().getClassLoader();
File file = new File(classLoader.getResource("/util.properties").getFile());
Properties props = new Properties();
props.load(new FileInputStream(file));