項目里引入多個版本依賴時,最后只會使用其中一個,一般可以通過排除不使用的依賴處理,但是如果需要同時使用多個版本,可以使用maven-shade-plugin解決。
以最典型的poi為例,poi版本兼容性很低,如果出現找不到類或者類未定義之類的錯誤,一般就是因為poi版本不兼容。
項目有這樣一個需求,需要使用poi-tl-ext實現word導出富文本,poi-tl-ext里使用的是poi 4.1.2,而原本項目里使用的是2.x,由于版本差異過大,使用新版本poi,會影響到系統的舊功能。
為了解決以上情況,需要同時使用兩個版本的poi,之所以存在沖突,是因為存在同包同名的類,因此只要將其中一個包重命名,就可以解決沖突,maven-shade-plugin是一個打包工具,可以用這個工具重命名指定報名,并生成新的依賴包。
具體操作:
1、新建一個maven項目,在pom.xml中引入依賴,設置重命名規則
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.test</groupId><artifactId>shade</artifactId><version>4.1.2</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding></properties><dependencies><dependency><groupId>io.github.draco1023</groupId><artifactId>poi-tl-ext</artifactId><version>0.4.22</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency></dependencies><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-shade-plugin</artifactId><version>3.2.4</version><executions><execution><phase>package</phase><goals><goal>shade</goal></goals><configuration><filters><filter><artifact>*:*</artifact><excludes><exclude>META-INF/*.SF</exclude><exclude>META-INF/*.DSA</exclude><exclude>META-INF/*.RSA</exclude></excludes></filter></filters><relocations><relocation><pattern>org.apache.poi</pattern><shadedPattern>shade.org.apache.poi</shadedPattern></relocation><relocation><pattern>com.deepoove.poi</pattern><shadedPattern>shade.com.deepoove.poi</shadedPattern></relocation></configuration></execution></executions></plugin></plugins></build>
</project>
2、執行mvn package生成jar包
3、在項目里引入生成的jar包
<dependency><groupId>com.test</groupId><artifactId>shade</artifactId><version>4.1.2</version><scope>system</scope><systemPath>${project.basedir}/src/main/lib/shade-4.1.2.jar</systemPath>
</dependency>
4、需要使用4.1.2版本的poi類時,import重命名后的包名