How does Maven work with Java 9 modules?

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?

Upvotes: 9

Views: 5887

Answers (1)

Andrew Sasha
Andrew Sasha

Reputation: 1294

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:

  1. Launch your application from module code:

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.

  1. Launch your application from non module code:

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 the Foo 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.

Upvotes: 4

Related Questions