Maven是一个Java项目的管理和构建工具:
Maven使用pom.xml定义项目内容,并使用预设的目录结构;
在Maven中声明一个依赖项可以自动下载并导入classpath;
Maven使用groupId,artifactId和version唯一定位一个依赖
依赖关系
compile | 说明 | 示例 |
---|---|---|
compile | 编译时需要用到该jar包(默认) | commons-logging |
test | 编译Test时需要用到该jar包) | junit |
runtime | 编译时不需要,但运行时需要用到) | mysql |
provided | 编译时需要用到,但运行时由JDK或某个服务器提供 | servlet-api |
//中国区用户可以使用阿里云提供的Maven镜像仓库。使用Maven镜像仓库需要一个配置,在用户主目录下进入.m2目录,创建一个settings.xml配置文件
<settings>
<mirrors>
<mirror>
<id>aliyun</id>
<name>aliyun</name>
<mirrorOf>central</mirrorOf>
<!-- 国内推荐阿里云的Maven镜像 -->
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
</mirror>
</mirrors>
</settings>
构建流程
mvn clean:清理所有生成的class和jar;
mvn clean compile:先清理,再执行到compile;
mvn clean test:先清理,再执行到test,因为执行test前必须执行compile,所以这里不必指定compile;
mvn clean package:先清理,再执行到package。
lifecycle相当于Java的package,它包含一个或多个phase;
phase相当于Java的class,它包含一个或多个goal;
goal相当于class的method,它其实才是真正干活的。
使用插件
插件名称 | 对应执行的phase |
---|---|
clean | clean |
compiler | compile |
surefire | test |
jar | package |
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.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.itranswarp.learnjava.Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
使用mvnw
mvn -N io.takari:maven:0.7.6:wrapper
发现多了mvnw、mvnw.cmd和.mvn目录,我们只需要把mvn命令改成mvnw就可以使用跟项目关联的Maven。例如:
./mvnw clean package