使用 maven shade plugin 解决 jar 或类的多版本冲突
java 应用经常会碰到的依赖的三方库出现版本冲突,下面举一个具体的例子。
Dubbo 是一个分布式的服务框架,其中的一种 rpc 实现(dubbo 协议)使用 hessian 3.2.0 来做序列化,另外一种实现(hsf协议)同样使用了 hesssian,但使用的版本是 3.0.14。如果现在一个应用中同时使用了 dubbo 协议和 hsf 协议,这个时候应用使用哪个版本的 hessian 呢?使用 3.2.0 可能会影响 hsf 协议,如果使用 3.0.14 那么 dubbo 协议会受影响。
maven shade plugin 能够把项目中依赖的 jar 包中的一些类文件打包到项目构建生成的 jar 包中,在打包的时候它有一个非常重要的特性是支持 relocation。relocation 的意思是把类重命名,比如把 com.caucho.hessian.io.HessianInput 重命名为 hidden.com.caucho.hessian.io.HessianInput,这样就不会出现冲突了。
下面是项目中 shade 插件的配置。
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>1.7.1</version> <executions> <execution> <id>shade-hessian</id> <goals> <goal>shade</goal> </goals> <configuration> <artifactSet> <includes> <include>hessian:hessian</include> </includes> </artifactSet> <createSourcesJar>true</createSourcesJar> <relocations> <relocation> <pattern>com.caucho</pattern> <shadedPattern>com.alibaba.dubbo.hsf.hessian.v3_0_14_bugfix</shadedPattern> </relocation> </relocations> </configuration> </execution> </executions> </plugin>