搬迁班级

如果 uber JAR 被重用为某个其他项目的依赖项,则直接在 uber JAR 中包含来自工件的依赖项的类可能会由于类路径上的重复类而导致类加载冲突。为了解决这个问题,可以重新定位包含在阴影工件中的类,以便创建其字节码的私有副本:

<project>
  ...
  <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>
              <relocations>
                <relocation>
                  <pattern>org.codehaus.plexus.util</pattern>
                  <shadedPattern>org.shaded.plexus.util</shadedPattern>
                  <excludes>
                    <exclude>org.codehaus.plexus.util.xml.Xpp3Dom</exclude>
                    <exclude>org.codehaus.plexus.util.xml.pull.*</exclude>
                  </excludes>
                </relocation>
              </relocations>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  ...
</project>

这指示插件通过移动相应的 JAR 文件条目并重写受影响的字节码,将类从包org.codehaus.plexus.util及其子包移动到包org.shaded.plexus.util中。Xpp3Dom类和其他一些类将保留在其原始包中。

也可以使用包含标签来缩小模式:

<project>
  ...
                <relocation>
                  <pattern>org.codehaus.plexus.util</pattern>
                  <shadedPattern>org.shaded.plexus.util</shadedPattern>
                  <includes>
                    <include>org.codehaud.plexus.util.io.*</include>
                  </includes>
                </relocation>
  ...
</project>