專案依賴中央倉庫沒有的第三方 JAR(如廠商私有 SDK、舊版專屬驅動),Maven 打包時預設不會包含。本文介紹兩種標準解法:system scope(舊專案相容)與 maven-install-plugin 安裝至本地倉庫(現代推薦),並說明打包插件設定細節。
<dependency>
<groupId>com.example</groupId>
<artifactId>legacy-lib</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/legacy-lib-1.0.jar</systemPath>
</dependency>
缺點:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>3.1.2</version>
<executions>
<execution>
<id>install-external-jars</id>
<phase>initialize</phase>
<goals><goal>install-file</goal></goals>
<configuration>
<file>${project.basedir}/lib/legacy-lib-1.0.jar</file>
<groupId>com.example</groupId>
<artifactId>legacy-lib</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<generatePom>true</generatePom>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
執行 mvn clean install 即會自動安裝,後續依賴可用普通 compile scope 引用。
mvn install:install-file \
-Dfile=lib/legacy-lib-1.0.jar \
-DgroupId=com.example \
-DartifactId=legacy-lib \
-Dversion=1.0 \
-Dpackaging=jar \
-DgeneratePom=true
若為 Spring Boot Fat Jar:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope> <!-- 僅 system scope 需要 -->
</configuration>
</plugin>
若為普通 maven-shade-plugin 或 maven-assembly-plugin:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals><goal>shade</goal></goals>
</execution>
</executions>
</plugin>
安裝至本地倉庫後,systemPath 依賴會被視為普通依賴正確打包。
mvn deploy:deploy-file 上傳。| 現象 | 原因 | 解決 |
|---|---|---|
| 打包後缺 Class | system scope 未傳遞、shade 插件未配置 | 改用 install-file + 普通依賴 |
| 版本衝突 | 多模組各自 install 同 artifactId 不同版本 | 統一私有倉庫、強制版本管理 |
| IDE 無法識別 | 本地倉庫更新後 IDE 未重新導入 | Maven Reload Project / Reimport |