How to build java 9 dependencies from maven depend

2020-02-29 11:28发布

问题:

Java9 has introduced a strong modularity similar to OSGI and Maven Dependecies.

Is there a maven plugin able to build the java 9 dependencies inspecting maven dependencies?

For example, from

<groupId>com.mycompany.app</groupId>
<artifactId>my-module</artifactId>
....
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>23.3-jre</version>
</dependency>

to

module my-module{
    requires com.google.guava;
    exports com.mycompany.app; 
}

I have read this article, but it is not so useful - How to express dependency in maven on java ee features for transition to Java 9?

回答1:

To answer the question precisely, the names of modules in the module-info as referenced in question like com.google.guavaper say are called the automatic module name. Generally, if you already have a jar with Java 8 for your app, let's say yourApp.jar with the above maven configuration. You can make use of the jdeps tool as:-

jdeps --generate-module-info <output-dir> /path/to/yourApp.jar

which would generate the module-info.java for your jar that you can further make use of while migrating the same project to Java 9.

The current corresponding plugin under the name maven-jdeps-plugin does not seem to be supporting this task. Though its still Work in Progress and this might pitch in, if seen effective by the owners to be introduced in the Maven workflow.

Edit :: Just in case you find the task useful the feature can be requested at MJDEPS tracker.



回答2:

There is a plugin in this github repo https://github.com/moditect/moditect allowing to do that.

In your example, put the following in the maven build:

<plugin>
  <groupId>org.moditect</groupId>
  <artifactId>moditect-maven-plugin</artifactId>
  <version>1.0.0.Alpha2</version>
  <executions>
    <execution>
      <id>add-module-infos</id>
      <phase>package</phase>
      <goals>
        <goal>add-module-info</goal>
      </goals>
      <configuration>
        <module>
          <moduleInfo>
            <name>com.mycompany.app.my.module</name>
          </moduleInfo>
        </module>
      </configuration>
    </execution>
  </executions>
</plugin>

and under target/moditect you may find the generated module-info.java