If I have all types of modules in my project (application, automatic and unnamed) how exactly Maven will work with them? Can I enforce Maven to treat some jars as automatic modules whereas other modules to stay in classpath. How to gradually migrate to module system with Maven?
Actually, we can! In this tutorial, we'll learn how to create a multi-module Maven application using Java modules.
What is Java 9 Module? A Module is a self-describing collection of Code, Data, and some Resources. It is a set of related Packages, Types (classes, abstract classes, interfaces etc) with Code & Data and Resources.
1 for LTS) requires Java 8 thus Maven jobs must be launched with a JDK >= 8. Soon (July-September 2022 timeframe) Jenkins will require Java 11 thus Maven jobs must be launched with a JDK >= 11.
There is very little difference between Maven Module and Maven Project. When we create a Maven module it is mandatory to specify a parent project. As soon as we specify the parent project, <modules> … </module> is added in pom.
Maven just manages your dependencies (jars). It doesn't care if dependencies are java modules or not.
The only way how Maven can help is if you launch your application through Maven (ex. mvn spring-boot:run
) then you can add some JVM parameters like --add-modules
.
If you are wondering about automatic and unnamed modules it's all depends how you launch your application, there are two ways how you can do that:
Since a module must require all of its dependencies and those can only be fulfilled by other named modules (i.e. not JARs on the class path) all dependencies of a modular JAR must be placed on the module path. Yes, even non-modular JARs, which will then get turned into automatic modules.
The interesting thing is that automatic modules can read the unnamed module, so their dependencies can go on the class path.
and because non-modular code does not express any dependencies, it will not resolve modules from the module path.
So if non-modular code depends on artifacts on the module path, you need to add them manually with the
--add-modules
option.For example if you want to use
ServiceLoader.load(Foo.class);
and you compile your application from non-modular code you'll have to add provider module of theFoo
class explicity to module graph with--add-modules
.
Note from The State of the Module System:
If a package is defined in both a named module and the unnamed module then the package in the unnamed module is ignored.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With