如何执行Java代码并捕获输出嵌入AsciiDoc技术书籍?
AsciiDoc编写Java技术书籍:代码执行、构建集成与同步方案
1. Java代码与AsciiDoc文件的项目结构选择
- 优先放在同一项目
- 优势:代码片段引用路径更简洁,无需跨项目配置复杂路径;修改Java代码后,能更顺畅地联动更新AsciiDoc中的代码片段与执行输出。
- 推荐布局:用
src/main/java存放示例代码,src/docs/asciidoc存放书籍文档,符合常规项目结构,维护起来更清晰。
- 分属独立项目的适用场景
- 仅当示例代码是完整的可复用工程,且与书籍文档为独立交付物时才考虑分开。但这种方式会增加维护成本,比如需要手动同步代码版本,不推荐常规使用。
2. Maven/Gradle集成AsciiDoc及同步更新方案
Maven集成
- 借助
asciidoctor-maven-plugin实现文档生成,配合exec-maven-plugin运行代码捕获输出:- 在
pom.xml的build/plugins中添加插件配置:
<plugin> <groupId>org.asciidoctor</groupId> <artifactId>asciidoctor-maven-plugin</artifactId> <version>2.2.6</version> <executions> <execution> <id>generate-docs</id> <phase>prepare-package</phase> <!-- 绑定到打包前的构建阶段 --> <goals> <goal>process-asciidoc</goal> </goals> </execution> </executions> <configuration> <sourceDirectory>src/docs/asciidoc</sourceDirectory> <outputDirectory>target/generated-docs</outputDirectory> <backend>html5</backend> <!-- 支持pdf、epub等其他格式 --> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>3.1.0</version> <executions> <execution> <id>run-example-code</id> <phase>process-classes</phase> <!-- 确保在文档生成前执行代码 --> <goals> <goal>java</goal> </goals> <configuration> <mainClass>com.example.MySampleCode</mainClass> <!-- 示例类全限定名 --> <outputFile>target/code-outputs/sample-output.txt</outputFile> <!-- 输出写入文件 --> </configuration> </execution> </executions> </plugin>- 同步更新逻辑:执行
mvn package时,会先编译运行Java代码生成输出文件,再生成包含最新代码片段(通过你已掌握的源文件引入方式)和输出内容的AsciiDoc文档。
- 在
Gradle集成
- 使用
org.asciidoctor.jvm.convert插件,配合自定义任务运行代码:- 在
build.gradle中引入插件:
plugins { id 'java' id 'org.asciidoctor.jvm.convert' version '3.3.2' }- 配置AsciiDoc生成任务:
asciidoctor { sourceDir file('src/docs/asciidoc') outputDir file('build/docs/asciidoc') backend = 'html5' }- 添加运行示例代码的自定义任务:
task runJavaExamples(type: JavaExec) { classpath = sourceSets.main.runtimeClasspath mainClass = 'com.example.MySampleCode' standardOutput = new FileOutputStream(file('build/code-outputs/sample-output.txt')) }- 同步更新逻辑:让
asciidoctor任务依赖runJavaExamples任务,执行gradle asciidoctor时,会先运行代码生成输出,再生成文档。修改Java代码后,重新执行构建任务即可自动更新AsciiDoc中的代码片段与输出。
- 在
代码片段与输出的同步细节
- 代码片段:在Java代码中用
// tag::example-snippet[]和// end::example-snippet[]标记需要引入的片段,AsciiDoc中通过include::../src/main/java/com/example/MySampleCode.java[tag=example-snippet]引用,修改代码后构建时会自动拉取最新片段。 - 输出内容:通过构建工具将代码执行结果写入文件,AsciiDoc中用
include::../target/code-outputs/sample-output.txt[]引入,构建流程会确保先更新输出文件再生成文档。
内容的提问来源于stack exchange,提问作者Basil Bourque
相关产品推荐
相关产品推荐

