项目里引入多个版本依赖时,最后只会使用其中一个,一般可以通过排除不使用的依赖处理,但是如果需要同时使用多个版本,可以使用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重命名后的包名