常用指令:
1、mvn -v 查看当前安装的maven版本号
2、mvn clean 清除编译生成target目录
3、mvn compile 编译生成.class字节码文件,target目录。
4、mvn test 运行测试类
5、mvn package 打包项目。
6、mvn install 把当前项目打包成jar,并保存到本地仓库中,可供其他项目引用依赖。
7、mvn archetype:gennerate 按照提示步骤初始化maven应用。
8、mvn archetype:gennerate -DgroupId= -DartifactId= -Dversion=版本号 -Dpackage=代码所在的包
9、mvn -U clean compile -Dmaven.test.skip=true; 编译并跳过单测
Maven生命周期:
1、clean清理项目:pre-clean执行清理前的工作。clean清理上一次构建生成的所有文件,post-clean:执行清理后的文件、
2、default构建项目:complie test package install阶段属于default生命周期
3、site生成项目站点
Maven插件的使用:
例子:使用source插件,实现在打包的同时,源码也一起打包。在pom.xml中配置;
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.4</version>
<!--绑定运行package(阶段)命令时,同时打包源码。-->
<!--将source绑定到default周期-->
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar-no-fork</goal>
<goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Maven依赖范围:
在pom.xml文件中添加依赖后就相当于把jar添加到应用的classPath下。maven分了三种classpath:编译、测试、运行
我们可以使用<scope></scope>来声明依赖范围:常用可选值为:
1、compile:默认值,编译,测试,运行都有效。
2、provided:在编译,测试时有效。运行时并不加入。servlet相关依赖就可以使用该范围,因为Web容器中已经包含,如果该依赖在运行时仍有效。可能会在Web容器启动时造成冲突。
3、runtime:在测试,运行时有效
4、test:仅在测试范围内有效。比如junit的jar;
比如:有些依赖仅在测试classPath使用,如Junit,我们在pom.xml可以这样声明
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
Maven依赖冲突:
1、短路优先:A->B->C->X(version:1.0.1) A->D->X(version:1.2.1)那么最终引的X.jar为1.2.1版本;
2、先声明先优先:如B->X(version:1.0.1) C->X(version:1.2.1) A同时依赖B和C时,在A的pom.xml中谁先声明就优先引用谁的的X依赖。
Maven的继承:
如果多个maven应用都会引用相同的依赖。为了各个项目中不重复定义依赖。可以使用maven继承。
依赖提供方:<dependency>
<groupId>com.test</groupId>
<artifactId>parent-pom</artifactId>
<version>1.0.2</version>
<!--这里必须是pom -->
<packaging>pom</packaging>
</dependency>
引用方:
<parent>
<groupId>com.test</groupId>
<artifactId>parent-pom</artifactId>
<version>1.0.2</version>
</parent>
为了方便开发,实战中我们经常把项目通用的框架依赖,以及必要的基础类,优先定义好。并打包成基础jar。下次启动新的应产品时,不需要再重复去配置pom.xml只需要继承基础jar即可。