Spring REST Docs:如何配置Asciidoctor任务正确引入生成的代码片段?
Your issue stems from the Asciidoctor build not resolving the {snippets} attribute correctly—so it can’t locate the generated code snippets referenced in your index.adoc. Here’s how to fix this in your build.gradle file:
Step 1: Configure the Asciidoctor Task with the Correct Snippets Path
You need to explicitly define the snippets attribute in your Asciidoctor task to point directly to the directory where your generated snippets are stored (build/generated-snippets/my-call). This tells Asciidoctor exactly where to look when it encounters the {snippets} variable in your .adoc files.
Here’s a complete, working configuration example:
plugins { id 'org.asciidoctor.jvm.convert' version '3.3.2' // Use the latest compatible version for your project } asciidoctor { // Optional: Explicitly set your Asciidoc source directory (default is src/docs/asciidoc) sourceDir file('src/docs/asciidoc') // Define attributes to resolve the {snippets} variable attributes { // Map {snippets} to your generated snippets root directory 'snippets' file('build/generated-snippets/my-call').absolutePath // Add optional formatting attributes as needed 'toc' 'left' 'numbered' '' 'docinfo' 'shared' } // Critical: Ensure Asciidoctor runs AFTER your snippets are generated // If using tools like Spring REST Docs, snippets are created during tests—so depend on the test task dependsOn test }
Why This Works
- The
attributesblock sets{snippets}to the absolute path of your generated snippets directory, eliminating relative path confusion between your source.adocfiles and the build-generated snippets. - The
dependsOn testline guarantees that your code snippets are generated (typically via integration tests for tools like Spring REST Docs) before Asciidoctor attempts to include them. Without this, Asciidoctor might run before the snippets exist, leading to unresolved directives.
Verify Path Alignment
Double-check that your snippet file structure matches what your include expects:
- Your
index.adocusesinclude::{snippets}/add-measurement/curl-request.adoc[] - This should map directly to
build/generated-snippets/my-call/add-measurement/curl-request.adoc
If the snippet file isn’t in that exact location, adjust either the snippets attribute path or the include path in index.adoc to match.
内容的提问来源于stack exchange,提问作者pixel

