You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Asciidoc中引入其他Maven模块的代码片段?

解决Asciidoctor在Maven多模块中跨模块引用代码片段的问题

我来帮你搞定这个跨模块引用代码的问题~在Maven多模块项目里,直接用类路径访问其他模块的源码确实容易出问题,因为Asciidoctor默认是基于当前模块的路径来查找文件的。下面给你两个实用的解决方案:

方法1:利用Maven属性定义跨模块源码路径

在当前模块的pom.xml中,添加一个指向目标模块源码目录的属性,这样就能在Asciidoc文件中直接引用这个属性了:

<properties>
  <!-- 替换成你的实际模块名,比如other-module -->
  <target-module-src>${project.parent.basedir}/other-module/src/main/java</target-module-src>
</properties>

然后在你的Asciidoc文档里,就可以用这个属性来引用目标模块的代码片段:

[source, java]
----
include::${target-module-src}/myPackage/mySubPackage/TargetClass.java[tag=myTag]
----

这个方法的核心是借助Maven的project.parent.basedir属性,它指向多模块项目的根目录,以此为基准就能准确定位到其他模块的源码。

方法2:用Maven资源插件复制目标模块源码

如果担心路径依赖的问题,也可以把目标模块的源码复制到当前模块的构建目录下,再进行引用:
在当前模块的pom.xml中添加Maven资源插件的配置:

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-resources-plugin</artifactId>
      <executions>
        <execution>
          <id>copy-target-module-source</id>
          <phase>generate-resources</phase>
          <goals>
            <goal>copy-resources</goal>
          </goals>
          <configuration>
            <!-- 复制到当前模块的target目录下的子文件夹 -->
            <outputDirectory>${project.build.directory}/target-module-src</outputDirectory>
            <resources>
              <resource>
                <!-- 目标模块的源码目录 -->
                <directory>${project.parent.basedir}/other-module/src/main/java</directory>
                <filtering>false</filtering>
              </resource>
            </resources>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

之后在Asciidoc里引用复制后的路径:

[source, java]
----
include::${project.build.directory}/target-module-src/myPackage/mySubPackage/TargetClass.java[tag=myTag]
----

这个方法的好处是完全基于当前模块的构建路径,避免了跨模块的路径依赖问题,适合复杂的多模块项目。

注意事项

  • 确保替换上述代码中的other-module为你实际的目标模块名称,路径也要对应正确的包结构
  • 如果使用Asciidoctor Maven插件,要确保插件的执行阶段在资源复制之后(比如prepare-package阶段),这样才能访问到复制后的源码

内容的提问来源于stack exchange,提问作者user9539816

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:21:37