- 一、Maven常用的命令
- mvn clean 清理
- mvn compile 编译
- mvn test 测试
- mvn package 打包
- mvn install 安装(将项目安装本地仓库)
- mvn deploy 发布(发布到服务器--私服、中央仓库(maven提供))
- 二、添加依赖获取坐标的方法
- .在联网个情况下通过http:www.mvnrepository.com来获取坐标
- 不联网的情况下通过开发工具MyEclipse--->Maven --->add dependency输入关键字例如struts2来获取,如果没有切换到Maven Repositores ---> local reponsitory ---> rebuild index 。(同时我们可以到Preference ---> Maven ----> 勾选上Download reponsites index on starup 来更新本地库但此操作可能会导致下载很多文件慎用)
- 三、依赖配置
- groupId、artifactId、version是依赖的基本坐标,缺一不可。
- type:依赖的类型,
- 对应坐标packaging,默认为jar
- <type>pom.lastUpdated</type> 表示使用最后更新,将不使用jar包,目前没用。
- optional:标记依赖是否可选。默认值false
- A->B->C,那么当A依赖于C时就可以设为可选。
- exclusions:排除传递依赖,解决jar冲突问题。
- 例如:spring bean 和 struts2 spring plugin
- scope:依赖范围
- compile:编译范围,默认scope,在classpath中存在
- provided:已提供范围,比如容器提供Servlet API
- runtime:运行时范围,编译不需要,接口与实现分离
- test:测试范围,单元测试环境需要
- system:系统范围,自定义构件,指定systemPath
- 四、依赖传递(依赖jar包冲突的排除)
打开pom.xml文件点击下面的Dependency Hierarchy选项选中冲突的其中一个版本的jar 右键 ---> Exclude Maven Artifact...然后再到pom.xml选项中将误选的另一个jar包的配置代码片段:
<exclusions>
<!-- 排除 struts spring 插件 使用 spring core -->
<exclusion>
<artifactId>spring-core</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
</exclusions>
删除掉即可。例如:spring beans 依赖 spring core使用 3.2.0 版本 而struts spring插件 依赖 spring core 使用 3.0.5 版本 默认情况配置在上面优先,开发中需要通过排除依赖,确定使用版本。
<dependencies>
<!-- 使用 struts插件 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.3.15.3</version>
<exclusions>
<!-- 排除 struts spring 插件 使用 spring core -->
<exclusion>
<artifactId>spring-core</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- 使用 spring bean -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.0.RELEASE</version>
//此处要删除的的误排除依赖的代码片段。很多情况下都会出现该种情况要注意!
<!--
<exclusions>
<!-- 排除 struts spring 插件 使用 spring core -->
<exclusion>
<artifactId>spring-core</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
</exclusions>
-->
</dependency>
</dependencies>
- 五、依赖范围(scope)
1.Maven项目在编译、运行和测试使用了三种不同的classpath
2.scope 用于确定maven执行 classpath 使用哪些 jar包
1 compile 编译、测试、运行 当前依赖jar都使用。默认值,一般适用于大部分情况。
2 test:测试时使用。例如:Junit
3 provided:编译、测试,注意:运行时没有。例如:servlet-api、jsp-api
servlet源码: 编写时,MyEclipse提供jar包
注意:使用Maven开发时是没有使用MyEclipse提供的servlet-api.jar 和 jsp-api.jar的所以必须要添加该两个jar包的依赖坐标并且scope的值一定为provided 因为运行的时候tomcat提供了该两个jar包没有设置<scope>provide</scope>的话会引起冲突。
4 runtime 测试和运行时使用,编译不使用。适合接口开发。例如:JDBC驱动。
5 system 从本地操作系统获得指定jar包,不依赖maven环境。不建议使用,不稳定。
- 六、依赖调节
第一原则:路径近者优先原则
第二原则:第一声明者优先原则当路径相等时,则由POM声明的依赖顺序决定