且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在多模块项目中读取属性文件

更新时间:2023-09-09 14:10:34

问题是资源文件(通常放在src/main/resources中的文件)最终出现在war文件的WEB-INF/classes子目录中.

The problem is that resources files (the ones you normally put in src/main/resources) wind up in the WEB-INF/classes subdirectory of the war-file.

现在,如果您尝试将propfilename设置为:

Now, if you try to set your propfilename to:

String propfilename = "WEB-INF/classes/com/xyz/comp/prop.properties" 

它仍然可靠地仍然无法正常工作(想到JWS),因为您正在使用Action类中的类加载器,而该类加载器在您尝试读取的jar/war中不存在

it will still not work reliably (JWS comes to mind) because you are using the classloader from the Action class, which is not present in the jar/war you are trying to read from.

执行此操作的正确方法是引入第三个模块/依赖项 您放置共享资源并让其他模块依赖的地方

The proper way of doing this is to introduce a third module/dependency where you put your shared resources and have the other modules depend on that.

对于JWS(Java Web Start)和其他使用类似类加载策略的框架,可以使用锚点"方法.

For JWS (Java Web Start) and other frameworks that use similar classloading strategies, you can use the "Anchor" approach.

用于类加载的锚定方法

由于要掌握给定类的类加载器通常需要您事先加载该类,因此一个技巧是将一个哑类放入仅包含资源(例如properties文件)的jar中.假设您在jar文件中具有以下结构:

Since getting hold of the classloader for a given class usually requires you to have loaded the class beforehand, a trick is to put a dummy class in a jar that only contains resources, such as properties files. Let's say you have this structure in a jar-file:

org/example/properties/a.properties
org/example/properties/b.properties
org/example/properties/c.properties

只需在jar中放入一个虚拟类,使其看起来像这样:

Just throw in a dummy class in the jar, making it look like this:

org/example/properties/Anchor.class
org/example/properties/a.properties
org/example/properties/b.properties
org/example/properties/c.properties

然后,通过其他代码,您现在可以执行此操作,并确保类加载按预期进行:

then, from other code you can now do this and be sure that classloading works as expected:

Properties properties = new Properties();
String propFile = "org/example/properties/a.properties";

ClassLoader classLoader = Anchor.class.getClassLoader();
InputStream propStream = classLoader.getResourceAsStream(propFile );

properties.load(propStream);

这是一种更强大的方法.

This is a more robust way of doing it.