Using Maven with Java 9 modules

When you bring Java 9 modules into the picture, you can see that there are two parallel concepts of modules here: the Maven concept of an artifact with the definition in pom.xml and the Java platform concept of a module with the module definition in module-info.java. However, these two work surprisingly well when you collapse the two and have each Maven project containing one Java 9 module.

Consider the following folder structure of a single Maven project. The code is in the lib folder. It is a typical Maven project. It has a pom.xml descriptor that contains the Maven coordinates for this artifact. However, it also has the module-info.java in the src/main/java folder that sets it up as a Java 9 module!

With this approach, the idea is to create a Maven artifact for each Java 9 module. This means that you'll need to come up with two separate names:

  • The coordinates for the Maven artifact--comprising of group name and artifact name
  • The name of the Java 9 module

Now, when it comes to establishing dependencies between two of these modules, you will need to specify dependencies in two places. Let's say, for example, that you have two Maven Java 9 projects called A and B. In order to specify that A is dependent on B, you need to do the following:

  • Add a <dependency> tag in the Maven pom.xml file of A specifying the Maven coordinates of B
  • Add a  requires declaration in the module-info.java file of A specifying the module name of B

The advantage of this approach is that Maven takes care of fetching the necessary artifacts and placing them in the module path. Then, the Java platform module system has everything it needs when the compiler or runtime executes! Note that this doesn't work if you miss either one of these two dependency configurations. If you forget to specify the Maven dependency, Maven will not fetch the artifact and place it in the module path. If you forget to add the requires declaration in module-info.java, your code cannot access the types in the dependency, even though Maven has made it available in the module path.

While this works great for one or two modules, this can also get tricky to manage when you are dealing with an application consisting of multiple modules. In such situations, we can leverage the multi-module project feature of Maven to better organize multiple Maven + Java 9 modules.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.27.251