1.依赖范围
一个项目要想使用别的jar包提供的功能,需要通过依赖将jar包引入到项目的classpath路径中。Maven提供了编译、测试、运行三种classpath,因此,依赖范围就是控制依赖与三种classpath的关系,依赖范围有以下5个取值。
• compile,缺省值,适用于所有阶段。
• provided,类似compile,编译和测试时有效,最后是在运行的时候不会被加入。官方举了一个例子,比如在JavaEE web项目中需要使用servlet的API,但是Tomcat中已经提供了这个jar,在编译和测试的时候需要使用这个api,但部署到tomcat的时候,如果还加入servlet构建就会产生冲突,这个时候就可以使用provided。
• runtime,适用运行和测试阶段,如JDBC驱动。
• test,只在测试时使用,用于编译和运行测试代码,不会随项目发布。
• system,与本机系统相关联,可移植性差,编译和测试时有效。
• import,导入,它只在dependencyManagement中使用,表示从其他pom中导入dependecy的配置,例如把A中的构建导入到B中。
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>maven</groupId>
<artifactId>B</artifactId>
<packaging>pom</packaging>
<name>B</name>
<version>1.0</version>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>maven</groupId>
<artifactId>A</artifactId>
<version>1.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
2.依赖传递
A依赖中包含B依赖,那么在引入A依赖的时候,B依赖也会传递过来,此种现象称为依赖传递,如spring-boot-starter-web依赖中包含内嵌的spring-boot-starter-tomcat依赖。

3.依赖排除
上面演示了依赖传递,但是如果在引入spring-boot-starter-web依赖的同时,不希望引入spring-boot-starter-tomcat依赖,这个时候就要是用exclusions 排除依赖列表。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
4.依赖冲突
(1).简介
由于依赖具有传递性,就会产生依赖冲突,Maven提供了最短路径和先声明先使用两种策略来解决依赖冲突。 比如,在demo项目中添加一个6.02版本的MySQL依赖,在demo1项目中添加一个6.06版本的MySQL依赖并引入demo依赖,然后在call项目中,引入demo1依赖,查看使用的MySQL版本。
(1).最短路径策略
1. 在demo项目中添加一个6.02版本的MySQL依赖,重新install

2. 在demo1项目中添加一个6.06版本的MySQL依赖,重新install

3. 在call项目中添加依赖demo1, demo1依赖demo,此时根据最短路径原则,call项目会依赖6.06版本
<dependencies>
<dependency>
<groupId>com.steven.maven</groupId>
<artifactId>demo1</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>

(2).先声明先使用策略
在call项目中依次引入demo和demo1依赖,demo依赖6.02版本,demo1依赖6.06版本,根据先声明先使用策略,call项目应该依赖demo的6.02版本。
<dependencies>
<dependency>
<groupId>com.steven.maven</groupId>
<artifactId>demo</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.steven.maven</groupId>
<artifactId>demo1</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>

2962

被折叠的 条评论
为什么被折叠?



