maven依赖
scope 依赖范围
-
其中依赖范围scope 用来控制依赖和编译,测试,运行的classpath的关系. 主要的是三种依赖关系如下:
- compile: 默认编译依赖范围。对于编译,测试,运行三种classpath都有效
- test:测试依赖范围。只对于测试classpath有效
- provided:已提供依赖范围。对于编译,测试的classpath都有效,但对于运行无效。因为由容器已经提供,例如servlet-api
- runtime:运行时提供。例如:jdbc驱动
依赖传递
- 假设目前有三个maven项目,分别是project.test1、project…test2、project.test3
project…test2的pom.xml添加对project.test1的依赖
<dependency>
<groupId>com.project</groupId>
<artifactId>project.test1</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
test1必须先安装到本地库,否则编译test2时会抛异常
- 直接依赖和间接依赖
- test2 依赖 test1,test3依赖test2
- test2 直接依赖 test1,test3间接依赖test1
- 当第二依赖的范围是compile的时候,依赖可以传递
- 当第二直接依赖的范围是test的时候,依赖不会得以传递
依赖冲突
假如test1使用junit4.10依赖,并且scope是compile,那test2,test3都可以使用test1的junit4.10,因为传递下来了
假如test2使用junit4.9依赖,那test3会使用【就近的一个依赖】,也就是使用junit4.9
可选依赖
<optional> true/false<optional> 是否可选,也可以理解为是否向下传递。
在依赖中添加optional选项决定此依赖是否向下传递,如果是true则不传递,如果是false就传递,默认为false
project…test2的pom.xml 文件:
<dependency>
<groupId>com.project</groupId>
<artifactId>project.test1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<optional> true<optional>
</dependency>
排除依赖
exclusions可用于排除依赖,注意exclusions是写在dependency中
<dependency>
<groupId>com.project</groupId>
<artifactId>project.test2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!--排除test2中test1的依赖 -->
<exclusions>
<exclusion>
<groupId>com.project</groupId>
<artifactId>project.test1</artifactId>
</exclusion>
</exclusions>
</dependency>
maven继承
继承
继承是为了消除重复,可以把很多相同的配置提取出来。例如:grouptId,version等
假设目前有四个maven项目,分别是project.parent、project.test1、project.test2、project.test3
要求test1、test2、test3整合到一个项目,并且从project.parent继承依赖
- parent聚合test1、test2、test3三个项目
<packaging>pom</packaging>
<modules>
<module>../project.test1</module>
<module>../project.test2</module>
<module>../project.test3</module>
</modules>
执行clean compile 进行验证,会同时编译test1、test2、test3三个项目
- test1、test2、test3分别关联parent项目
<parent>
<groupId>com.project</groupId>
<artifactId>project.parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
会自动继承父类的依赖jar
- 父工程统一管理依赖
在父工程中通过配置dependencies依赖,子工程可以直接继承使用
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependencies>
如果把父类依赖放在<dependencyManagement>中管理,则子类不会自动成父类的依赖
project.parent的pom.xml 文件:
<parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
</parent>