Hi I have a project which has two modules with the following structure
project
│
└───Module1
│ |---abc.jsp
│
│
├───Module2
│----src.main.
|
|---java.
| |---com.xyz.comp
| │----------Action.java
|
|
└───resources
|---com.xyz.comp
│ prop.properties
Now My Module1 has a dependency on war of Module2(Module2 is an independent war file). My problem is that the abc.jsp of Module1 submits to the Action.java of Module2. In which when I try to access prop.properties gives null pointer exception.
public static void test(){
Properties properties = new Properties();
String propfilename = "com/xyz/comp/prop.properties";
try {
ClassLoader contextClassLoader = Action.class.getClassLoader();
InputStream prpoStream= contextClassLoader.getResourceAsStream(propfilename );
properties.load(propertiesStream);
// bunch of other code
} catch (Exception e) {
}
}
The propStream is always null because it cannot find the file. Am i giving the path wrong or since this is called from another module the classloader does not have access to this module files?
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();
来源:https://stackoverflow.com/questions/33821074/read-properties-file-in-multi-module-project