问题在于资源文件(通常是您放入的文件src/main/resources
)会出现在WEB-INF/classes
war文件的子目录中。
现在,如果您尝试将其设置propfilename
为:
String propfilename = "WEB-INF/classes/com/xyz/comp/prop.properties"
它仍然不能 可靠地 工作(想到JWS),因为您正在使用Action
该类中的类加载器,而该类加载器在您尝试读取的jar / war中不存在。
这样做的正确方法是引入第三个模块/依赖性,在其中放置共享资源并使其他模块依赖于此。
对于JWS(Java Web Start)和其他使用类似类加载策略的框架,可以使用“锚点”方法。
由于掌握给定类的类加载器通常需要您事先加载该类,因此一个技巧是将虚拟类放入仅包含资源(例如properties
文件)的jar中。假设您在jar文件中具有以下结构:
org/example/properties/a.properties
org/example/properties/b.properties
org/example/properties/c.properties
只需在jar中放入一个虚拟类,使其看起来像这样:
org/example/properties/Anchor.class
org/example/properties/a.properties
org/example/properties/b.properties
org/example/properties/c.properties
然后,从其他代码中,您现在可以执行此操作,并确保类加载按预期进行:
Properties properties = new Properties();
String propFile = "org/example/properties/a.properties";
ClassLoader classLoader = Anchor.class.getClassLoader();
InputStream propStream = classLoader.getResourceAsStream(propFile );
properties.load(propStream);
这是一种更强大的方法。