如果引用了在 Maven 远程仓库中没有的 jar 包,比如自己组使用的类包,或者是一些历史遗留的包,在使用 Maven 构建过程中就容易遇到找不到类之类的问题。比如我遇到过的问题就有:
- 编译时找不到 xxx 类
- 进行测试时找不到 xxx 类
针对这两个问题的一些解决方法
编译
只针对编译的时候可以通过配置插件来设置扩展(即本地 jar)的位置,假设我们的 jar 包放在 lib 文件夹里,配置例子如下
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<compilerArgs>
<arg>-extdirs</arg>
<arg>${basedir}/lib</arg>
</compilerArgs>
</configuration>
</plugin>
这里配置 <compilerArgs>
,添加编译参数 -extdirs ${basedir}/lib
测试
我暂时没有发现通过配置 surefire 插件来解决测试时引入本地 jar 的方法,所以用别的方式,下面两种方式都能解决编译跟测试的问题
pom.xml 中添加本地依赖
<project>
...
<dependencies>
<dependency>
<groupId>sun.jdk</groupId>
<artifactId>tools</artifactId>
<version>1.5.0</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
</dependencies>
...
</project>
依赖配置中 scope
为 system,systemPath
指定 jar 包路径。不过这种引入依赖的方式已被标记为过时的。
- 安装本地 jar 包到本地仓库
执行
mvn install:install-file -Dfile=lib/localjar-1.0.0.jar -DgroupId=org.group -DartifactId=localjar -Dversion=1.0.0 -Dpackaging=jar
就可以安装 localjar-1.0.0.jar 到本地仓库了,然后在 pom.xml 中添加依赖就行,配置和普通的依赖配置是一样的。这里的 groupId、artifactId、version 等都可以随便指定的,只是影响本地仓库生成目录结构而已,pom.xml 增加依赖时保持一致就行。