read properties file in multi module project

浪尽此生 提交于 2019-12-02 04:05:24

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.

Now, if you try to set your propfilename to:

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

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.

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

The Anchor approach for classloading

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

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.

Try this :

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!