read properties file in multi module project

后端 未结 2 1437
旧时难觅i
旧时难觅i 2021-01-23 08:46

Hi I have a project which has two modules with the following structure

project
│ └───Module1 │ |---abc.jsp │
│ ├───Mod

相关标签:
2条回答
  • 2021-01-23 09:40

    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.

    0 讨论(0)
  • 2021-01-23 09:48

    Try this :

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

    0 讨论(0)
提交回复
热议问题