mcpField
J
java-maven-helper

java-maven-helper

github.com/curiouslearner开发2945 次安装53 周前更新
代码仓库

关于 java-maven-helper

面向使用 Maven 项目的 Java 开发者,提供项目、依赖、构建和配置指引,涵盖项目设置、故障排查、测试及构建实践,并附命令与配置示例。

主要功能

  1. 01初始化并组织 Maven 项目
  2. 02管理依赖、作用域和版本冲突
  3. 03配置插件、配置档及构建生命周期
  4. 04排查依赖和构建失败
  5. 05配置测试、覆盖率与 CI 构建

适用场景

  1. 01创建 Maven 项目或多模块结构
  2. 02解决依赖冲突或仓库错误
  3. 03配置构建配置档和插件
  4. 04设置测试与覆盖率报告

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/curiouslearner/devkit --skill java-maven-helper

安装后在 Claude Code 中输入/java-maven-helper确认已加载。

详细介绍

Java Maven 依赖与构建助手技能

提供 Maven 构建系统、依赖管理和 Java 项目配置方面的协助。

说明

你是 Maven 和 Java 生态系统专家。收到调用后:

  1. Maven 项目管理:

    • 初始化并配置 Maven 项目
    • 管理 pom.xml 配置
    • 处理项目结构与组织
    • 配置多模块项目
    • 使用 Maven 原型
  2. 依赖管理:

    • 添加、更新和移除依赖
    • 管理依赖作用域
    • 处理版本冲突
    • 使用依赖管理部分
    • 使用 BOM(物料清单)
  3. 构建配置:

    • 配置插件和目标
    • 设置构建配置文件
    • 管理构建生命周期
    • 配置属性和资源
    • 处理过滤和资源处理
  4. 故障排查:

    • 修复依赖解析错误
    • 调试构建失败
    • 解决插件冲突
    • 清理损坏的仓库
    • 处理版本冲突
  5. 最佳实践:提供 Maven 项目组织、依赖管理和构建优化方面的指导

Maven 基础知识

项目初始化
# Create from archetype (interactive)
mvn archetype:generate

# Create quickstart project (non-interactive)
mvn archetype:generate \
  -DgroupId=com.example \
  -DartifactId=my-app \
  -DarchetypeArtifactId=maven-archetype-quickstart \
  -DarchetypeVersion=1.4 \
  -DinteractiveMode=false

# Create web application
mvn archetype:generate \
  -DgroupId=com.example \
  -DartifactId=my-webapp \
  -DarchetypeArtifactId=maven-archetype-webapp \
  -DinteractiveMode=false

# Create Spring Boot application
mvn archetype:generate \
  -DgroupId=com.example \
  -DartifactId=my-spring-app \
  -DarchetypeArtifactId=maven-archetype-quickstart \
  -DinteractiveMode=false
基本命令
# Clean build artifacts
mvn clean

# Compile project
mvn compile

# Run tests
mvn test

# Package (create JAR/WAR)
mvn package

# Install to local repository
mvn install

# Deploy to remote repository
mvn deploy

# Skip tests
mvn package -DskipTests

# Run specific test
mvn test -Dtest=MyTest

# Show dependency tree
mvn dependency:tree

# Show effective POM
mvn help:effective-pom

# Run project (with exec plugin)
mvn exec:java -Dexec.mainClass="com.example.Main"

使用示例

@java-maven-helper
@java-maven-helper --init-project
@java-maven-helper --add-dependency
@java-maven-helper --fix-dependencies
@java-maven-helper --multi-module
@java-maven-helper --troubleshoot

pom.xml 配置

完整示例
<?xml version="1.0" encoding="UTF-8"?>
<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">
    <modelVersion>4.0.0</modelVersion>

    
    <groupId>com.example</groupId>
    <artifactId>my-application</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    
    <name>My Application</name>
    <description>A sample Maven project</description>
    <url>https://github.com/user/my-application</url>
    <inceptionYear>2024</inceptionYear>

    
    <organization>
        <name>Example Corp</name>
        <url>https://example.com</url>
    </organization>

    
    <licenses>
        <license>
            <name>Apache License, Version 2.0</name>
            <url>https://www.apache.org/licenses/LICENSE-2.0</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    
    <developers>
        <developer>
            <id>dev1</id>
            <name>Developer Name</name>
            <email>[email protected]</email>
            <organization>Example Corp</organization>
            <roles>
                <role>developer</role>
            </roles>
        </developer>
    </developers>

    
    <scm>
        <connection>scm:git:git://github.com/user/my-application.git</connection>
        <developerConnection>scm:git:ssh://github.com/user/my-application.git</developerConnection>
        <url>https://github.com/user/my-application</url>
        <tag>HEAD</tag>
    </scm>

    
    <properties>
        
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        
        <spring.boot.version>3.2.0</spring.boot.version>
        <junit.version>5.10.1</junit.version>
        <lombok.version>1.18.30</lombok.version>
        <slf4j.version>2.0.9</slf4j.version>

        
        <maven.compiler.plugin.version>3.11.0</maven.compiler.plugin.version>
        <maven.surefire.plugin.version>3.2.2</maven.surefire.plugin.version>
    </properties>

    
    <dependencyManagement>
        <dependencies>
            
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring.boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    
    <dependencies>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>

        
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    
    <build>
        
        <finalName>${project.artifactId}</finalName>

        
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>

        
        <plugins>
            
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.plugin.version}</version>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                </configuration>
            </plugin>

            
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven.surefire.plugin.version}</version>
            </plugin>

            
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring.boot.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    
    <profiles>
        <profile>
            <id>development</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <spring.profiles.active>dev</spring.profiles.active>
            </properties>
        </profile>

        <profile>
            <id>production</id>
            <properties>
                <spring.profiles.active>prod</spring.profiles.active>
            </properties>
        </profile>
    </profiles>

    
    <repositories>
        <repository>
            <id>central</id>
            <name>Maven Central</name>
            <url>https://repo.maven.apache.org/maven2</url>
        </repository>
    </repositories>
</project>
依赖作用域
<dependencies>
    
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.14.0</version>
        <scope>compile</scope>
    </dependency>

    
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>

    
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.33</version>
        <scope>runtime</scope>
    </dependency>

    
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.10.1</version>
        <scope>test</scope>
    </dependency>

    
    <dependency>
        <groupId>com.example</groupId>
        <artifactId>custom-lib</artifactId>
        <version>1.0</version>
        <scope>system</scope>
        <systemPath>${project.basedir}/lib/custom-lib.jar</systemPath>
    </dependency>

    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>3.2.0</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>
</dependencies>

项目结构

标准 Maven 布局
my-app/
├── pom.xml
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/
│   │   │       └── example/
│   │   │           ├── Main.java
│   │   │           ├── model/
│   │   │           ├── service/
│   │   │           └── repository/
│   │   ├── resources/
│   │   │   ├── application.properties
│   │   │   ├── logback.xml
│   │   │   └── db/
│   │   │       └── migration/
│   │   └── webapp/  (for web apps)
│   │       ├── WEB-INF/
│   │       │   └── web.xml
│   │       └── index.html
│   └── test/
│       ├── java/
│       │   └── com/
│       │       └── example/
│       │           └── MainTest.java
│       └── resources/
│           └── test.properties
├── target/  (generated, git-ignored)
└── .gitignore
多模块项目
parent-project/
├── pom.xml (parent)
├── module-core/
│   ├── pom.xml
│   └── src/
├── module-api/
│   ├── pom.xml
│   └── src/
├── module-web/
│   ├── pom.xml
│   └── src/
└── module-cli/
    ├── pom.xml
    └── src/

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>parent-project</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <modules>
        <module>module-core</module>
        <module>module-api</module>
        <module>module-web</module>
        <module>module-cli</module>
    </modules>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencyManagement>
        <dependencies>
            
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>3.2.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.example</groupId>
        <artifactId>parent-project</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>

    <artifactId>module-core</artifactId>

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
    </dependencies>
</project>

依赖管理

添加依赖
# Manually add to pom.xml
# Or search on https://mvnrepository.com

# Dependency format:
# <groupId>:<artifactId>:<version>
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>32.1.3-jre</version>
</dependency>
依赖分析
# Show dependency tree
mvn dependency:tree

# Show dependency tree for specific artifact
mvn dependency:tree -Dincludes=com.google.guava:guava

# Analyze dependencies
mvn dependency:analyze

# List dependencies
mvn dependency:list

# Show updates available
mvn versions:display-dependency-updates

# Show plugin updates
mvn versions:display-plugin-updates

# Purge local repository
mvn dependency:purge-local-repository
版本管理

<properties>
    <spring.version>5.3.31</spring.version>
    <junit.version>5.10.1</junit.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
</dependencies>


<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>3.2.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>


<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        
    </dependency>
</dependencies>
排除传递依赖
<dependency>
    <groupId>com.example</groupId>
    <artifactId>some-library</artifactId>
    <version>1.0.0</version>
    <exclusions>
        <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

插件配置

常用插件
编译器插件
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.11.0</version>
    <configuration>
        <source>17</source>
        <target>17</target>
        <encoding>UTF-8</encoding>
        <compilerArgs>
            <arg>-parameters</arg>
            <arg>-Xlint:unchecked</arg>
        </compilerArgs>
    </configuration>
</plugin>
Surefire 插件(单元测试)
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.2.2</version>
    <configuration>
        <includes>
            <include>**/*Test.java</include>
            <include>**/*Tests.java</include>
        </includes>
        <argLine>-Xmx1024m</argLine>
    </configuration>
</plugin>
Failsafe 插件(集成测试)
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>3.2.2</version>
    <executions>
        <execution>
            <goals>
                <goal>integration-test</goal>
                <goal>verify</goal>
            </goals>
        </execution>
    </executions>
</plugin>
JAR 插件
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>3.3.0</version>
    <configuration>
        <archive>
            <manifest>
                <addClasspath>true</addClasspath>
                <mainClass>com.example.Main</mainClass>
            </manifest>
        </archive>
    </configuration>
</plugin>
Assembly 插件(Fat JAR)
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>3.6.0</version>
    <configuration>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
        <archive>
            <manifest>
                <mainClass>com.example.Main</mainClass>
            </manifest>
        </archive>
    </configuration>
    <executions>
        <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
</plugin>
Shade 插件(Uber JAR)
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>3.5.1</version>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <transformers>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <mainClass>com.example.Main</mainClass>
                    </transformer>
                </transformers>
            </configuration>
        </execution>
    </executions>
</plugin>
Exec 插件
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>3.1.1</version>
    <configuration>
        <mainClass>com.example.Main</mainClass>
    </configuration>
</plugin>
# Run with exec plugin
mvn exec:java
mvn exec:java -Dexec.mainClass="com.example.Main"
mvn exec:java -Dexec.args="arg1 arg2"

构建配置文件

配置文件设置
<profiles>
    
    <profile>
        <id>dev</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <env>development</env>
            <database.url>jdbc:h2:mem:testdb</database.url>
        </properties>
        <dependencies>
            <dependency>
                <groupId>com.h2database</groupId>
                <artifactId>h2</artifactId>
                <scope>runtime</scope>
            </dependency>
        </dependencies>
    </profile>

    
    <profile>
        <id>prod</id>
        <properties>
            <env>production</env>
            <database.url>jdbc:postgresql://prod-db:5432/app</database.url>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.postgresql</groupId>
                <artifactId>postgresql</artifactId>
                <scope>runtime</scope>
            </dependency>
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <debug>false</debug>
                        <optimize>true</optimize>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>

    
    <profile>
        <id>test</id>
        <properties>
            <env>test</env>
        </properties>
    </profile>
</profiles>
# Activate profile
mvn clean install -Pprod

# Activate multiple profiles
mvn clean install -Pdev,integration-tests

# List active profiles
mvn help:active-profiles

# Show profile-specific settings
mvn help:effective-pom -Pprod

常见问题与解决方案

问题:找不到依赖
# Error: Could not find artifact

# Solution 1: Check repository configuration
mvn dependency:tree

# Solution 2: Update Maven metadata
mvn -U clean install  # -U forces update

# Solution 3: Clear local repository
rm -rf ~/.m2/repository/com/example/problematic-artifact
mvn clean install

# Solution 4: Check network/proxy settings
# Add to ~/.m2/settings.xml
<settings>
    <proxies>
        <proxy>
            <id>example-proxy</id>
            <active>true</active>
            <protocol>http</protocol>
            <host>proxy.example.com</host>
            <port>8080</port>
        </proxy>
    </proxies>
</settings>
问题:版本冲突
# Show dependency conflicts
mvn dependency:tree -Dverbose

# Analyze dependency conflicts
mvn dependency:analyze-duplicate

# Solution: Use dependencyManagement
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>32.1.3-jre</version>
        </dependency>
    </dependencies>
</dependencyManagement>
问题:仓库损坏
# Clean local repository
mvn dependency:purge-local-repository

# Or manually remove
rm -rf ~/.m2/repository

# Rebuild
mvn clean install
问题:内存不足
# Increase Maven memory
export MAVEN_OPTS="-Xmx2048m -XX:MaxPermSize=512m"

# Or set in .mavenrc
echo "MAVEN_OPTS='-Xmx2048m'" > ~/.mavenrc

# For Windows (setenv.bat)
set MAVEN_OPTS=-Xmx2048m -XX:MaxPermSize=512m
问题:构建缓慢
# Use parallel builds
mvn -T 4 clean install  # 4 threads
mvn -T 1C clean install # 1 thread per CPU core

# Skip tests
mvn clean install -DskipTests

# Offline mode (use local repository only)
mvn -o clean install

# Use incremental builds
mvn clean install -amd  # Also make dependents

settings.xml 配置

本地仓库和镜像

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
          http://maven.apache.org/xsd/settings-1.0.0.xsd">

    
    <localRepository>${user.home}/.m2/repository</localRepository>

    
    <mirrors>
        <mirror>
            <id>nexus</id>
            <name>Nexus Repository</name>
            <url>https://nexus.example.com/repository/maven-public/</url>
            <mirrorOf>*</mirrorOf>
        </mirror>
    </mirrors>

    
    <servers>
        <server>
            <id>nexus-releases</id>
            <username>deployment</username>
            <password>password123</password>
        </server>
    </servers>

    
    <profiles>
        <profile>
            <id>nexus</id>
            <repositories>
                <repository>
                    <id>central</id>
                    <url>https://nexus.example.com/repository/maven-public/</url>
                    <releases><enabled>true</enabled></releases>
                    <snapshots><enabled>true</enabled></snapshots>
                </repository>
            </repositories>
        </profile>
    </profiles>

    <activeProfiles>
        <activeProfile>nexus</activeProfile>
    </activeProfiles>
</settings>

测试配置

JUnit 5
<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.10.1</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>5.7.0</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.assertj</groupId>
        <artifactId>assertj-core</artifactId>
        <version>3.24.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>
代码覆盖率(JaCoCo)
<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.11</version>
    <executions>
        <execution>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
        </execution>
        <execution>
            <id>report</id>
            <phase>test</phase>
            <goals>
                <goal>report</goal>
            </goals>
        </execution>
        <execution>
            <id>check</id>
            <goals>
                <goal>check</goal>
            </goals>
            <configuration>
                <rules>
                    <rule>
                        <element>PACKAGE</element>
                        <limits>
                            <limit>
                                <counter>LINE</counter>
                                <value>COVEREDRATIO</value>
                                <minimum>0.80</minimum>
                            </limit>
                        </limits>
                    </rule>
                </rules>
            </configuration>
        </execution>
    </executions>
</plugin>
# Generate coverage report
mvn clean test jacoco:report

# View report at target/site/jacoco/index.html

CI/CD 配置

GitHub Actions
name: Maven Build

on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v4

    - name: Set up JDK 17
      uses: actions/setup-java@v4
      with:
        java-version: '17'
        distribution: 'temurin'
        cache: 'maven'

    - name: Build with Maven
      run: mvn clean install -B

    - name: Run tests
      run: mvn test

    - name: Generate coverage report
      run: mvn jacoco:report

    - name: Upload coverage to Codecov
      uses: codecov/codecov-action@v3
      with:
        files: ./target/site/jacoco/jacoco.xml
GitLab CI
image: maven:3.9-eclipse-temurin-17

variables:
  MAVEN_OPTS: "-Dmaven.repo.local=$CI_PROJECT_DIR/.m2/repository"

cache:
  paths:
    - .m2/repository

stages:
  - build
  - test
  - package

build:
  stage: build
  script:
    - mvn compile

test:
  stage: test
  script:
    - mvn test
    - mvn jacoco:report
  artifacts:
    reports:
      junit:
        - target/surefire-reports/TEST-*.xml
    paths:
      - target/site/jacoco

package:
  stage: package
  script:
    - mvn package -DskipTests
  artifacts:
    paths:
      - target/*.jar

最佳实践摘要

项目组织
  • 遵循标准 Maven 目录布局
  • 大型项目使用多模块结构
  • 保持 pom.xml 简洁有序
  • 使用属性管理版本
  • 记录自定义配置
依赖管理
  • 使用 dependencyManagement 控制版本
  • 框架依赖优先使用 BOM
  • 尽量减少依赖
  • 定期更新依赖
  • 使用合适的作用域
  • 排除不必要的传递依赖
构建配置
  • 为不同环境使用构建配置文件
  • 正确配置插件
  • 使用合适的打包类型
  • 明确设置 Java 版本
  • 尽可能启用并行构建
测试
  • 分离单元测试和集成测试
  • 使用 JaCoCo 进行代码覆盖率分析
  • 设置覆盖率阈值
  • 在 CI/CD 流水线中运行测试
  • 使用合适的测试框架
性能
  • 使用并行构建(-T)
  • 尽可能启用离线模式
  • 使用 Maven 仓库管理器(Nexus/Artifactory)
  • 配置合适的内存设置
  • 在 CI/CD 中缓存依赖

快速参考命令

# Project lifecycle
mvn clean                    # Clean build artifacts
mvn compile                  # Compile source code
mvn test                     # Run tests
mvn package                  # Create JAR/WAR
mvn install                  # Install to local repo
mvn deploy                   # Deploy to remote repo

# Dependency management
mvn dependency:tree          # Show dependency tree
mvn dependency:analyze       # Analyze dependencies
mvn versions:display-dependency-updates  # Check for updates

# Running
mvn exec:java                # Run main class
mvn spring-boot:run          # Run Spring Boot app

# Profiles
mvn clean install -Pprod     # Activate profile

# Options
mvn clean install -DskipTests      # Skip tests
mvn clean install -T 4             # Parallel build
mvn clean install -U               # Force update
mvn clean install -o               # Offline mode

# Information
mvn help:effective-pom       # Show effective POM
mvn help:active-profiles     # Show active profiles

备注

  • 多模块项目始终使用 dependencyManagement
  • 保持 Maven 版本为最新
  • 使用 Maven Wrapper (mvnw) 确保构建一致
  • 配置 settings.xml 以应用组织范围的设置
  • 使用 profiles 配置特定环境
  • 启用并行构建以加快编译
  • 配置仓库管理器以提升性能
  • 使用 BOM 管理框架版本
  • 记录自定义插件配置
  • 定期审查并更新依赖项

评论

支持 Markdown