You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Maven的pom.xml中定义项目为Jar包并排除测试代码

How to Configure Maven to Package a Jar with Only 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/java is compiled to target/classes and included in the final Jar during the package phase.
  • Code in src/test/java is only compiled during the test phase, lives in target/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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:27:51