本文講述在maven項(xiàng)目中使用本地jar包的4種方法:
- 1.手動添加jar到本地maven庫
- 2.使用 maven-install-plugin
- 3.在dependency中使用system scope
- 4.創(chuàng)建一個(gè)本地maven庫
手動添加jar到本地maven庫
第一種方法是使用mvn命令將jar包添加到本地方法庫滤祖,方法如下:
mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> -DartifactId=<artifact-id> -Dversion=<version>
參數(shù)如下:
- <path-to-file>: Path to the JAR to install
- <group-id>: Group id of the JAR to install
- <artifact-id>: Artifact id of the JAR to install
- <version>: Version of the JAR
例子如下:
mvn install:install-file -DgroupId=com.example -DartifactId=auth -Dversion=1.0.0 -Dpackaging=jar -Dfile=Athena-1.0.0-jar-with-dependencies.jar
使用 maven-install-plugin
這個(gè)方法是在pom.xml中使用maven-install-plugin,在“initialize”階段安裝jar包蚓胸,可以把jar包放在一個(gè)指定的路徑下旺芽,例子如下:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>install-file</goal>
</goals>
<configuration>
<packaging>jar</packaging>
<artifactId>Athena</artifactId>
<groupId>com.example.zodiac</groupId>
<version>1.0.0</version>
<file>${basedir}/lib/Athena-1.0.0-jar-with-dependencies.jar</file>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
經(jīng)過各種嘗試亚斋,發(fā)現(xiàn)一種情況:在一個(gè)pom.xml文件中使用maven-install-plugin的同時(shí)定義對該jar包的依賴,這種方式編譯無法通過。
變通方式是在root module的pom.xml中使用maven-install-plugin,然后在子module中使用dependency蝶俱,例子如下:
<dependency>
<groupId>com.example.zodiac</groupId>
<artifactId>Athena</artifactId>
<version>1.0.0</version>
<type>jar</type>
</dependency>
在dependency中使用system scope
這種方法比較簡單笛匙,直接上例子:
<dependency>
<groupId>com.example.zodiac</groupId>
<artifactId>Athena</artifactId>
<version>1.0.0</version>
<type>jar</type>
<scope>system</scope>
<systemPath>${basedir}/lib/Athena-1.0.0-jar-with-dependencies.jar</systemPath>
</dependency>
創(chuàng)建一個(gè)本地maven庫
這種方法簡單粗暴侨把,在pom.xml文件中定義一個(gè)新的maven庫,然后根據(jù)maven的存儲方式將jar包放在指定的路徑下:
<repositories>
<repository>
<id>local</id>
<name>local</name>
<url>file:///${pom.basedir}/lib/</url>
<layout>default</layout>
<snapshots><enabled>false</enabled></snapshots>
</repository>
</repositories>
然后將jar包放在路徑:${pom.basedir}/lib/com/example/zodiac/Athena/1.0.0/Athena-1.0.0-.jar
ps:由于Athena-1.0.0-jar-with-dependencies.jar命名不符合maven的規(guī)范妹孙,所以需要將Athena-1.0.0-jar-with-dependencies.jar重命名為Athena-1.0.0-.jar或者修改依賴jar的version為:1.0.0-jar-with-dependencies