maven | scope | 犀牛的博客
source link: https://benpaodewoniu.github.io/2023/01/30/maven10/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
scope
元素
上面讲完了 optional
元素的使用,再来看看 scope
的使用。
scope
元素主要用来控制依赖的使用范围,指定当前包的依赖范围和依赖的传递性,也就是哪些依赖在哪些classpath
中可用。常见的可选值
- compile
- provided
- runtime
- system
compile(编译)
默认值。compile
表示对应依赖会参与当前项目的编译、测试、运行等,是一个比较强的依赖。打包时通常会包含该依赖,部署时会打包到lib
目录下。比如:spring-core
这些核心的jar
包。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
test(测试)
scope
为test
表示依赖项目仅参与测试环节,在编译、运行、打包时不会使用。最常见的使用就是单元测试类了:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
类似单元测试这样的依赖,如果不设置scope
为test
,很显然它们会被打包、发布,但其实真是环境中并无什么作用。
runntime(运行时)
runntime
仅仅适用于运行和测试环节,在编译环境下不会被使用。比如编译时只需要JDBC API
的jar
,而只有运行时才需要JDBC
驱动实现。
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
<scope>runtime</scope>
</dependency>
provided(已提供)
provided
适合在编译和测试的环境,和compile
功能相似,但provide
仅在编译和测试阶段生效,provide
不会被打包,也不具有传递性。
比如:上面讲到的spring-boot-devtools
、servlet-api
等,前者是因为不需要在生产中热部署,后者是因为容器已经提供,不需要重复引入。
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
system
system
范围依赖与provided
类似,不过依赖项不会从maven
仓库获取,而需要从本地文件系统提供。使用时,一定要配合systemPath
属性。不推荐使用,尽量从Maven
库中引用依赖。
<dependency>
<groupId>sun.jdk</groupId>
<artifactId>tools</artifactId>
<version>1.5.0</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
scope
依赖的传递性
上面讲解scope
的不同参数值,针对这些参数值,在多个项目中的依赖传递性如下:
其中B
依赖A
,C
依赖B
,传递性的关键是B
依赖A
时所设置的scope
值,当B
采用不同的值时对应的依赖关系如下:当B
通过test
或provided
依赖A
时,C
不依赖A
;当B
通过runtime
或compile
依赖A
时,C
依赖A
;
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK