How can I use maven to include classes from a sibl

2019-07-07 19:19发布

问题:

I have Maven project with a parent module and two children: Service and API. The Service module is a WAR and contains all of the source files for the project, while the API module exists purely to build a jar containing a subset of classes from the Service module, and to deploy that jar to a local maven repo.

I've tried a combo of the maven-dependency-plugin and the maven-assembly-plugin to copy over the Service war and include it in the deployed API JAR, but I'm struggling to find a way to pull in just a specific set of classes from the Service module without roping in the entire fat WAR.

From API's pom.xml:

<plugins>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
      <execution>
        <id>copy-dependencies</id>
        <phase>package</phase>
        <goals>
          <goal>copy-dependencies</goal>
        </goals>
        <configuration>
          <excludeGroupIds>...</excludeGroupIds>
          <outputDirectory>${project.build.directory}/lib</outputDirectory>
        </configuration>
      </execution>
    </executions>
  </plugin>
  <plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <executions>
      <execution>
        <goals>
          <goal>single</goal>
        </goals>
        <phase>package</phase>
      </execution>
    </executions>
    <configuration>
      <descriptors>
        <descriptor>assembly.xml</descriptor>
      </descriptors>
    </configuration>
  </plugin>
</plugins>

I've thought about building the slim JAR using the maven-jar-plugin from the Service module's pom, but this seems like bad practice. Suggestions?

回答1:

You should rather take out the implementation details from the war and put in a separate module.

.
├── pom.xml
├── service-api
|   ├── pom.xml
|   └── src
|       └── main
|           └── java
|               └── com
|                   └── stackoverflow
|                       └── SomeDao.java
├── service-impl
|   ├── pom.xml
|   └── src
|       └── main
|           └── java
|               └── com
|                   └── stackoverflow
|                       └── SomeDaoImpl.java
└── service-web
    ├── pom.xml
    └── src
        └── main
            └── webapp
                └── WEB-INF
                    └── web.xml

Let service-impl depend on service-api. And service-web will depend on the service-impl.



回答2:

I recommend that your API project actually contain the classes that you want to deploy, and the Service module depend on it. If you want to modularize your project (and you should), do it the way Maven wants, and not trying to hack apart a single codebase.