三、maven-shade-plugin解决依赖冲突
最后如何来配置和使用maven-shade-plugin将Guava映射成我们自己定制的Jar包,实现与中间件Guava的隔离。整个的过程还是比较清晰明了的,主要是创建一个Maven工程,引入依赖,配置我们要发布的仓库地址,引入编译打包插件和maven-shade-plugin插件,配置映射规则(标签之间部分),然后编译打包发布到Maven仓库。pom.xml的配置如下:
4.0.0
<groupId>com.shaded.example</groupId>
<artifactId>guava-wrapper</artifactId>
<version>${guava.wrapper.version}</version>
<name>guava-wrapper</name>
<url>https://example.com/guava-wrapper</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!- 版本与 guava 版本基本保持一致 ->
<guava.wrapper.version>27.1-jre</guava.wrapper.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.1-jre</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.2</version>
<executions>
<execution>
<id>default-jar</id>
<goals>
<goal>jar</goal>
</goals>
<phase>package</phase>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<id>default-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.1</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<!-- 重命名规则配置 -->
<relocations>
<relocation>
<!-- 源包路径 -->
<pattern>com.google.guava</pattern>
<!-- 目标包路径 -->
<shadedPattern>com.google.guava.wrapper</shadedPattern>
</relocation>
<relocation>
<pattern>com.google.common</pattern>
<shadedPattern>com.google.common.wrapper</shadedPattern>
</relocation>
<relocation>
<pattern>com.google.thirdparty</pattern>
<shadedPattern>com.google.wrapper.thirdparty</shadedPattern>
</relocation>
</relocations>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"/>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<distributionManagement>
<!- Maven仓库配置,略 ->
</distributionManagement>
项目引入这个新打包的guava-wrapper后,import选择从这个包导入我们需要的相关类即可。如下: com.vivo.internet guava-wrapper 27.1-jre 亚马逊测评 www.yisuping.cn