jar包不同的版本不兼容的时候如何保留两个版本

815 阅读1分钟

如图这样的问题,我们该怎样解决呢,

Question:

假设一个项目中的pom文件引入了A(version1.0)和B(version1.0)两个依赖,但是B有依赖A(version2.0),这个时候分情况考虑了

  1. 如果依赖A2.0 兼容了 A1.0 那么我们直接去除依赖A1.0即可

  2. 如果依赖A2.0 不兼容 A1.0, 我们去除A1.0,需要改动旧代码,我们排除B1.0 中的 A2.0 又是用不了A2.0 提供的新功能

image.png

solution:

借助poi 3.17说明问题
项目中已经存在poi 3.17的依赖,而poi-tl最低poi版本4.12,将项目中已有的3.17升级到4.12时,旧代码出错,但是不升级就无法使用poi-tl。

<dependencies>
    <!-- 项目中已经引用3.17 -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.17</version>
    </dependency>
    <!-- 这次新加的功能需要使用poi-tl,最低poi版本4.12 -->
    <dependency>
        <groupId>com.deepoove</groupId>
        <artifactId>poi-tl</artifactId>
        <version>1.10.0</version>
    </dependency>
</dependencies>


我们要做的就是把poi-tl中的高版本poi包改个名字,同时poi-tl中引用的地方也改名(自动),并且代码中用高本版的地方也改个名(手动)。



1.  创建一个空maven项目,引入poi-tl的依赖:
<dependencies>
    <!-- 这次新加的功能需要使用poi-tl -->
    <dependency>
        <groupId>com.deepoove</groupId>
        <artifactId>poi-tl</artifactId>
        <version>1.10.0</version>
    </dependency>
</dependencies>


2.  引入插件并且配置好修改的方式:
<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>
                        <createDependencyReducedPom>true</createDependencyReducedPom>
                        <relocations>
                            <relocation>
                                <!-- 改名前 -->
                                <pattern>org.apache.poi</pattern>
                                <!-- 改名后 -->
                                <shadedPattern>shaded.org.apache.poi</shadedPattern>
                            </relocation>
                        </relocations>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

3. 这时target目录中会有两个包,一个是original开头的原本包,因为我们没有新建类,所以这个包是空的。  另一个是和`artifactId-version.jar`的包,`artifactId`和`version`是本项目创建时填写的坐标。


image.png

然后把这个shaded包引入项目中使用即可,如果要使用高版本poi只需要`import shaded.org.apache.poi`下的类即可。

其他

参考文章:https://www.cnblogs.com/lixin-link/p/15507326.html
我的测试demo:test-multijar