如何在Maven的pom.xml中定义项目为Jar包并排除测试代码
src/main/java Content Hey there! Let me break this down for you clearly—this is straightforward to set up with Maven's default behavior, and I’ll walk you through every step.
1. Define the Project as a Jar Package
First, you just need to add the <packaging> element to your pom.xml, right under the root <project> tag. This tells Maven to build a Jar artifact for your project, and as you noted, it will automatically use the Maven Jar plugin behind the scenes without any explicit configuration needed.
Here’s a snippet showing where to place this:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <!-- Your project basics: groupId, artifactId, version --> <!-- This line sets the project to build a Jar --> <packaging>jar</packaging> <!-- Dependencies, build settings, etc. --> </project>
2. Default Behavior Already Excludes src/test/java
Great news—you don’t need any extra work to keep test code out of your Jar! Maven’s standard build lifecycle separates production and test code by design:
- Code in
src/main/javais compiled totarget/classesand included in the final Jar during thepackagephase. - Code in
src/test/javais only compiled during thetestphase, lives intarget/test-classes, and is never included in the main distribution Jar. It’s solely for running your tests, not for release.
Optional: Explicitly Enforce Exclusion (If You Want)
While the default setup already does what you need, if you ever want to explicitly confirm or lock in this behavior, you can add a minimal configuration for the Maven Jar plugin (though this is usually unnecessary):
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.3.0</version> <!-- Use the latest stable version --> <configuration> <!-- Explicitly include only production class files --> <includes> <include>**/*.class</include> </includes> <!-- Test classes are in target/test-classes, so they won't be picked up here --> </configuration> </plugin> </plugins> </build>
Once you run mvn package, you’ll find your Jar in the target directory—only containing your production code from src/main/java (plus any resources in src/main/resources, if you have them).
内容的提问来源于stack exchange,提问作者Developer

