在Maven中引入外部的jar包的时候,由于这时候的jar包并不在maven的本地仓库或者云仓库,所以maven不能识别jar包。这时候需要将本地jar包引入,并且打包的时候一起将外部的jar包一并打包。
主要有以下三种方法:
1、将外部的jar包安装到maven 的本地仓库或者私有仓库。具体操作如下:
使用maven执行如下命令:
mvm install:install-file
-Dfile=E:\ChromeDownloads\xx-xx-sdk-1.2.0.jar
-DgroupId=com.xx.xx
-DartifactId=xx-sdk
-Dversion=1.2.0
-Dpackaging=Jar
参数说明:
Dfile:外部jar包的路径(使用绝对路径)
DgroupId :该jar包在仓库中的groupId
DartifactId:该jar包在仓库中的artifactId
Dversion:该jar包在仓库中的version(版本)
Dpackaging:打包方式(这里是JAR)
2、在项目的maven配置文件(pom.xml)中直接引入。
在配置文件中指定引入外部jar包:
<dependency>
<groupId>com.xx.xx</groupId>
<artifactId>xx-sdk</artifactId>
<version>1.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/xx-sdk-1.2.0.jar</systemPath>
</dependency>
参数说明:
scope:依赖范围控制,控制依赖的使用、加载范围。当值为system的时候,表明该依赖从本地路径查找,不会去maven仓库查找加载,所以需要配合systemPath标签使用,指明路径。且不会将该依赖打包。
systemPath:本地依赖jar包的路径,和scope值为system的时候配合使用。${project.basedir}表明当前项目的根路径。
通过scope指明依赖的加载是通过system的,可以解决maven引入外部依赖的问题。但是打包的时候仍然不会将这个外部的jar包一起package。
3、在maven 的compiler插件中增加编译阶段的jar包路径范围。
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<encoding>UTF-8</encoding>
<compilerArguments>
<!-- 编译时使用 lib 目录下的外部 jar 包 -->
<extdirs>${project.basedir}/lib</extdirs>
</compilerArguments>
</configuration>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
主要的配置就是complierArguments中的extdirs指明增加的jar包路径。
PS:方法3和方法2差不多,和方法2比较,方法3统一配置了maven编译时候的外部jar包路径,能够免去外部jar包多的时候,每个依赖都要指明外部路径。
在打包的时候将scope作用范围为system的jar包一起打包
方法2和方法3虽然能够在编译运行的时候加载外部的jar包,但是打包的时候并不会把这个外部依赖的jar包一起package,所以需要配置一下,打包的时候将scope作用范围为system的外部jar包一起package。
在Springboot项目中:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
主要的就是includeSystemScope这个需要设置为true,表明打包的时候将作用范围为system的依赖也一起打包。
在单独的Maven项目中:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.10</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>compile</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<!--指定打包出来的jar包目录 -->
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/lib</outputDirectory>
<!--这里指定包含 system scope -->
<includeScope>system</includeScope>
</configuration>
</execution>
</executions>
</plugin>