如何用Maven解压依赖Jar并将类文件打包至War指定目录
Got it, let's solve this problem step by step. Assuming you're using Maven (the most common build tool for Java JAR/WAR projects), here are the exact configurations you need to modify in module-B's pom.xml to extract module-A's classes directly into your WAR file's target directory, instead of bundling the module-A JAR itself.
Step 1: Unpack module-A's JAR into module-B's compile output
Use the Maven Dependency Plugin to unpack module-A's class files into target/classes (the directory that gets packaged into WEB-INF/classes in the WAR). Add this to the <build><plugins> section of module-B's pom.xml:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>unpack-module-a-classes</id> <phase>prepare-package</phase> <!-- Run right before packaging --> <goals> <goal>unpack</goal> </goals> <configuration> <artifactItems> <artifactItem> <!-- Replace with your actual module-A coordinates --> <groupId>com.yourorg</groupId> <artifactId>module-A</artifactId> <version>1.0.0</version> <outputDirectory>${project.build.directory}/classes</outputDirectory> <includes>**/*.class</includes> <!-- Only extract class files --> <!-- Add <includes>**/*.properties</includes> if you need resource files too --> </artifactItem> </artifactItems> </configuration> </execution> </executions> </plugin>
Step 2: Exclude module-A's JAR from the WAR
To avoid having both the extracted classes and the original JAR in your WAR, configure the Maven War Plugin to exclude module-A's JAR from the WEB-INF/lib folder:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <packagingExcludes>WEB-INF/lib/module-A-*.jar</packagingExcludes> </configuration> </plugin>
For Gradle Users
If you're using Gradle instead, add this to module-B's build.gradle file:
war { // Extract module-A's classes into WEB-INF/classes from zipTree(configurations.runtimeClasspath.find { it.name.startsWith('module-A') }) { include '**/*.class' into 'WEB-INF/classes' } // Exclude the original module-A JAR from the WAR exclude 'WEB-INF/lib/module-A-*.jar' }
Key Notes
- Replace the placeholder coordinates (
groupId,artifactId,version) with your actual module-A details. - If you need to extract non-class resources (like
.propertiesor.xmlfiles), adjust the<includes>(Maven) orinclude(Gradle) patterns to include those file types. - Run
mvn clean package(Maven) or./gradlew clean war(Gradle) to build the modified WAR—you'll now see module-A's classes directly underWEB-INF/classesin the WAR, with no module-A JAR inWEB-INF/lib.
内容的提问来源于stack exchange,提问作者Subhashc

