一个maven项目中直接引入两个版本的jar包
一个maven项目中直接引入两个版本的jar包
问题来源
需要使用老版本的poi,目前系统是新版本的poi。
不想启动新的服务。想要特定方法用老版本poi
解决方式
- 创建了一个 Maven 子模块
- 该模块引入了 poi-3.9 的依赖,老版本的poi
- 把这个模块打包成一个独立的 jar,并且里面的 org.apache.poi 被重命名为 com.shaded.poi.v39.org.apache.poi
具体代码
第一步:配置 maven-shade-plugin 插件
<build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-shade-plugin</artifactId><version>3.5.0</version><executions><execution><phase>package</phase><goals><goal>shade</goal></goals><configuration><!-- 重命名 org.apache.poi 到 com.shaded.poi.v39.org.apache.poi --><relocations><relocation><pattern>org.apache.poi</pattern><shadedPattern>com.shaded.poi.v39.org.apache.poi</shadedPattern></relocation></relocations><!-- 只打包指定的依赖 --><artifactSet><includes><include>org.apache.poi:poi</include><include>org.apache.poi:poi-ooxml</include><include>org.apache.poi:poi-scratchpad</include></includes></artifactSet><!-- 输出文件名自定义 --><outputFile>${project.build.directory}/${project.artifactId}-${project.version}-shaded.jar</outputFile></configuration></execution></executions></plugin></plugins>
</build>
第二步:执行构建命令生成 shaded jar
mvn clean package
构建完成后,你会在 target/ 目录下看到类似这样的文件:
your-module-name-1.0.0-shaded.jar
所有 org.apache.poi 开头的类都被重命名为 com.shaded.poi.v39.org.apache.poi
它包含了 poi-3.9、poi-ooxml-3.9、poi-scratchpad-3.9 的全部类
和主项目的 poi 高版本完全隔离,不会冲突
第三步,引入到新项目
直接放入 lib 并手动添加依赖(IDE 配置)
之后可以正常调用