前言
常常,我们在使用 Maven 构建、编译和打包项目后,都会部署到对应的 服务环境上,然而有时会遇到以下3个问题:
- jar 包冲突
- jar 包太大
- 缺少jar 依赖
在解决上面3个问题之前,一起来看看 Maven dependency scope 的 6个 可用范围
- compile 默认scope。将会把这个依赖的相关包都引入。
- provided 编译时,不会将这个依赖相关的包引入。
- runtime 编译不需要依赖项,但是用于运行时。
- test 表示正常使用应用程序不需要依赖关系。
- system 和 provided 类似,这里只需要指定jar 的路径,编译时会引用这个 jar 包信息。
- import 编译时,依赖其他项目的 <dependencyManagement>。
内容
举例介绍他们的适用场景。
- compile:编译时,会把所有和这个项目相关的依赖引入,适用于本地测试,避免本地运行不起来。
<dependency>
<groupId>io.flinkspector</groupId>
<artifactId>flinkspector-datastream_2.11</artifactId>
<version>1.7.2</version>
<scope>compile</scope>
</dependency>
- provided:编译时,不会把所有和这个项目相关的依赖引入,适用于生产中,避免 Jar 冲突和 jar 包太大。
<dependency>
<groupId>io.flinkspector</groupId>
<artifactId>flinkspector-datastream_2.11</artifactId>
<version>1.7.2</version>
<scope>provided</scope>
</dependency>
- runtime:编译时,不会把依赖和本项目引入,适用于测试。
<dependency>
<groupId>io.flinkspector</groupId>
<artifactId>flinkspector-datastream_2.11</artifactId>
<version>1.7.2</version>
<scope>runtime</scope>
</dependency>
- test:编译时,无依赖,仅适用于测试编译和执行阶段。
<dependency>
<groupId>io.flinkspector</groupId>
<artifactId>flinkspector-datastream_2.11</artifactId>
<version>1.7.2</version>
<scope>test</scope>
</dependency>
- system:编译时,会引入用户指定路径的 Jar 包,和 compile 类似
<dependency>
<groupId>io.flinkspector</groupId>
<artifactId>flinkspector-datastream_2.11</artifactId>
<version>1.7.2</version>
<scope>system</scope>
<systemPath>/Volumes/e/lib/spark-assembly-2.4.3.jar </systemPath>
</dependency>
所以基本可以回答开始的 3个问题:
- jar 包冲突:使用 provided
- jar 包太大:使用 provided,并且把 有关的依赖包放到 环境变量对应的目录下
- 缺少jar 依赖:使用 compile
参考
https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html