Accessing resource files from external modules

cen :

So far until non-modularized java, you would simply put a file in src/main/java/resources make sure it is in classpath and then load it with

file = getClass().getClassLoader().getResourceAsStream("myfilename"); 

from pretty much anywhere in the classpath.

Now with modules, the plot thickens.

My project setup is the following:

module playground.api {
    requires java.base;
    requires java.logging;
    requires framework.core;
}

Config file is placed inside src/main/resources/config.yml.

Project is run with

java -p target/classes:target/dependency -m framework.core/com.framework.Main

Since the main class does not reside in my own project, but in an external framework module, it can't see config.yml. Now the question is, is there a way to somehow put my config file into the module or open it up? Do I have to change the way file is loaded by framework upstream?

I tried using "exports" or "opens" in module-info but it wants to have a package name, not a folder name.

How to achieve this in best practical way so it would work as in Java 8 and with as little changes as possible?

Naman :

While you are using the java command to launch an application as follows:-

java -p target/classes:target/dependency -m framework.core/com.framework.Main 
  • you are specifying the modulepath using the option -p aternate for --module-path which would look up into target/classes and target/dependency for your modules.

  • Alongside, using -m alternate for --module specifies the initial module to resolve with the name framework.core and constructs the module graph with the main class to execute explicitly listed as com.framework.Main.

Now, the problem here seems to be that the module framework.core doesn't requires or read playground.api module because of which the module graph doesn't include the desired module consisting of the actual resource config.yml.

As suggested by @Alan, a good way to list out the module resolution output during startup is to make use of the --show-module-resolution option.


I just naively tried to opens src/main/resources, doesn't compile ofc

Since the resource in your module is at the root level, it is, therefore, not encapsulated and does not need to be opened or exported to any other module.

In your case, you just need to make sure that the module playground.api ends up in the module graph and then the resource would be accessible to the application. To specify root modules to resolve in addition to the initial module, you can make use of the --add-modules option.


Hence the overall solution to work for you along with some debugging shall be :

java --module-path target/classes:target/dependency 
     --module framework.core/com.framework.Main
     --add-modules playground.api
     --show-module-resolution

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=430271&siteId=1