Maven构建工具

Maven是Java开发中最常用的项目依赖管理工具。

虽然喜新厌旧的更喜欢Gradle,可在Java项目中还是会常常用到Maven,干脆做些记录。

基础

安装

解压安装包后需要设置环境变量:M2_HOME,之后把M2_HOME/bin加到PATH。

# Ubuntu
sudo apt install maven

mvn -version

通过wrapper的方式,其他人可以不用安装Maven。

# 安装设置wrapper
mvn -N io.takari:maven:wrapper

# 执行wrapper
./mvnw clean package

运行命令

运行mvn会在本地目录解析pom.xml(POM即Project Object Model),依赖下载到位于 ~/.m2/repository的本地仓库。

mvn test
mvn package
mvn clean package

# IDEA支持
mvn idea:idea

一些选项说明:

  • -X,–debug
  • -o 离线模式,不检查线上依赖更新
  • -ff, –fail-fast
# --projects  指定只安装某子项目
mvn install -pl sub_project

镜像加速

修改下面的其中一个配置:

  • ~/.m2/settings.xml
  • maven根目录下的conf文件夹中的setting.xml文件

内容如下:

<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
 xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">  
<mirrors>
    <mirror>
        <id>nexus-tencentyun</id>
        <name>Nexus tencentyun</name>
        <url>http://mirrors.cloud.tencent.com/nexus/repository/maven-public/</url>
        <mirrorOf>central</mirrorOf>
        <mirrorOf>central</mirrorOf>
    </mirror>
    <mirror>      
        <id>alimaven</id>      
        <name>aliyun Central</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
        <mirrorOf>central</mirrorOf>
    </mirror>
</mirrors>
</settings>

生命周期

生命周期包含各种阶段,各阶段通过插件和目标实现具体的任务。

常用阶段/phase:

  • clean: 先清除之前的构建目标,即./target/目录
  • compile: 编译源码
  • package: 创建jar部署包
  • test: 运行测试
  • install: 编译,构建并安装到本地仓库
  • deploy: 部署到远程仓库等

一些生命周期目标通过插件实现。

通过模板快速创建项目

通过archtype插件生成项目模板:

mvn archetype:generate

快速创建Java项目

mvn archetype:generate
	-DgroupId=com.xulizhao.demo
	-DartifactId=java-practice
	-DarchetypeArtifactId=maven-archetype-quickstart
	-DinteractiveMode=false

忽略测试

mvn clean install -DskipTests
mvn package -Dmaven.test.skip=true
# maven.test.skip同时控制maven-compiler-plugin和maven-surefire-plugin两个插件的行为,即跳过编译和测试

或者

  <properties>
    <skipTest>true</skipTest>
  </properties>

打包时忽略错误:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <skip>true</skip><!--跳过单元测试-->
        <!--<testFailureIgnore>true</testFailureIgnore>--><!--忽略单元测试类的编译错误-->
    </configuration>
</plugin>

配置pom.xml

GAV

即构成一个POM或依赖的基本三要素,来确定一个唯一的标识:

  • groupId
  • artifactId
  • version
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.xulizhao</groupId>
  <artifactId>demo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>demo-project</name>
   <packaging>jar</packaging>

常用属性

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

多模块项目

<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.xulizhao</groupId>
    <artifactId>guava</artifactId>
    <version>0.1.0-SNAPSHOT</version>
    <name>guava</name>

    <parent>
        <groupId>com.xulizhao</groupId>
        <artifactId>parent-java</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../parent-java</relativePath>
    </parent>
    <modules>
        <module>core-java-collections</module>
        <module>core-java-networking</module>
    </modules>

</project>

打包

打包jar

<build>
		<finalName>demoApp</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.11.0</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>

			<!-- Make this jar executable -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
				  <archive>
					<manifest>
						<mainClass>com.xulizhao.demo.App</mainClass>
					</manifest>
				  </archive>
				</configuration>
			</plugin>
		</plugins>
	</build>

打包依赖

默认不会添加项目依赖到jar,

复制依赖到文件夹

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <!--<mainClass></mainClass>-->
                        <classpathPrefix>dependency-jars/</classpathPrefix>
                    </manifest>
                    <manifestEntries>
                        <Class-Path>.</Class-Path>
                    </manifestEntries>
                </archive>
            </configuration>
        </plugin>
        <!-- 复制依赖库 -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>3.6.0</version>
            <executions>
              <execution>
                <id>copy-dependencies</id>
                <phase>package</phase>
                <goals>
                    <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                  <includeScope>runtime</includeScope>
                  <outputDirectory>${project.build.directory}/dependency-jars/</outputDirectory>
                </configuration>
              </execution>
            </executions>
        </plugin>

使用插件 Maven Shade Plugin

打包成fat jar(也叫Uber Jar)并添加Main入口,这里的shade意味着类会被重命名以避免依赖间冲突。

一些例子参考官网Maven Shade Plugin

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-shade-plugin</artifactId>
	<version>3.4.1</version>
	<executions>
		<!-- Attach the shade into the package phase -->
		<execution>
			<phase>package</phase>
			<goals>
				<goal>shade</goal>
			</goals>
			<configuration>
                <!--去掉不必要的类,缩小jar尺寸.需要JDK8+ -->
                <minimizeJar>true</minimizeJar>
				<transformers>
					<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
						<mainClass>com.xulizhao.demo.App</mainClass>
					</transformer>
				</transformers>
                <artifactSet>
                    <includes>
                        <include>org.apache.jmeter:*</include>
                    </includes>
                    <excludes>
                        <exclude>org.slf4j:*</exclude>
                        <exclude>org.apache.logging.log4j:*</exclude>
                </excludes>
                </artifactSet>
			</configuration>
		</execution>
	</executions>
</plugin>

提取依赖classes

使用maven-assembly插件,仅适用于依赖库不多的情况。

<plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
 </plugin>

打包资源文件

   <build>
    <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.dll</include>
                    <include>**/*.so.*</include>
                </includes>
            </resource>
        </resources>
    </build>

依赖

显示依赖关系

# 在控制台显示依赖树
mvn dependency:tree -Dverbose

# 输出到文件
mvn dependency:tree -Dverbose -DoutputFile=/home/xulz/maven-dependencies

依赖的版本管理

# 显示依赖新版本
mvn versions:display-dependency-updates
# 更新到最新发布版
mvn versions:use-latest-releases

依赖本地库

    <dependency>
      <groupId>com.xulizhao.demo</groupId>
      <artifactId>mylib</artifactId>
      <version>1.0</version>
      <scope>system</scope>
      <systemPath>${project.basedir}/libs/mylib-0.0.1-SNAPSHOT.jar</systemPath>
    </dependency>

指定版本

<dependency>
        <groupId>net.sf.json-lib</groupId>
        <artifactId>json-lib</artifactId>
        <version>2.4</version>
        <classifier>jdk15</classifier>
</dependency>

插件

常用插件

解决错误:Unresolved plugin:‘org.apache.maven.plugins:maven….’ 增加dependency,然后pom.xml右键-reload project

	<dependencies>
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.11.0</version>
        </dependency>
    </dependencies> 

使用技巧

修改Windows默认库位置

# 修改 C:\Users\xulz\.m2\settings.xml
  <!-- localRepository
  | The path to the local repository maven will use to store artifacts.
  |
  | Default: ~/.m2/repository
  -->
 <localRepository>d:/data/.m2/repository</localRepository>

库检索

资源