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

能否将spring-auto-restdocs与Swagger/SpringFox、swagger2markup结合使用?

Can Spring Auto REST Docs work with Swagger/SpringFox & swagger2markup?

Great question! The short answer is yes—you can absolutely combine these tools to meet your requirements, though it takes some targeted configuration to align their behaviors. Let’s walk through your two key goals with practical steps:

1. Align Swagger UI examples with Spring REST Docs’ snippet style

Spring Auto REST Docs generates examples from your live MockMvc tests, while Swagger/SpringFox typically uses default values or arbitrary placeholders for its UI examples. To make them match, you’ll need to sync the test-generated examples into Swagger’s metadata:

  • Step 1: Capture examples with Spring Auto REST Docs
    First, set up your MockMvc tests to generate request/response snippets as usual. For example:

    @Test
    void createUser() throws Exception {
        mockMvc.perform(post("/users")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(new User("Alice", "alice@example.com"))))
            .andExpect(status().isCreated())
            .andDo(autoDocumentation.document(
                requestFields(),
                responseFields()
            ));
    }
    

    This will generate JSON example files in your target/generated-snippets directory.

  • Step 2: Inject examples into Swagger/SpringFox
    Create a custom SpringFox plugin to read these generated examples and replace Swagger’s default ones. For instance, an OperationBuilderPlugin that loads the snippet files and sets them as the operation’s request/response examples:

    @Component
    public class RestDocsExamplePlugin implements OperationBuilderPlugin {
        private final ObjectMapper objectMapper;
        private final ResourceLoader resourceLoader;
    
        // Constructor injection for dependencies
    
        @Override
        public void apply(OperationContext context) {
            // Extract API path/method to find matching snippet files
            String path = context.requestMappingPattern();
            HttpMethod method = context.httpMethod();
            // Load the generated request/response example JSON
            Resource requestExample = resourceLoader.getResource("classpath:generated-snippets" + path + "/" + method.name().toLowerCase() + "/request-body.json");
            if (requestExample.exists()) {
                JsonNode exampleJson = objectMapper.readTree(requestExample.getInputStream());
                context.operationBuilder().requestBody(RequestBody.builder()
                    .examples(Collections.singletonMap(MediaType.APPLICATION_JSON_VALUE,
                        Example.builder().value(exampleJson).build()))
                    .build());
            }
            // Repeat for response examples
        }
    
        @Override
        public boolean supports(DocumentationType delimiter) {
            return DocumentationType.SWAGGER_2.equals(delimiter);
        }
    }
    

    This ensures Swagger UI displays the exact same examples generated by your tests, matching Spring REST Docs’ style.

2. Generate docs from POJO Javadocs (no Swagger annotations)

Spring Auto REST Docs is designed to work with Javadocs out of the box—you don’t need Swagger annotations like @ApiModelProperty at all. Here’s how to set this up:

  • Enable Javadoc parsing
    Ensure your build tool is configured to generate Javadocs and make them available to Spring Auto REST Docs. For Maven, add this to your pom.xml:

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>3.5.0</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    
  • Configure Spring Auto REST Docs to use Javadocs
    The AutoDocumentation feature automatically scans your POJOs’ field Javadocs to populate field descriptions in the generated snippets. For example, if your POJO looks like this:

    public class User {
        /**
         * Full name of the user (must be at least 2 characters)
         */
        private String name;
        /**
         * Valid email address for user communication
         */
        private String email;
    
        // Constructors, getters, setters
    }
    

    Spring Auto REST Docs will pull those Javadoc comments into the request-fields and response-fields snippets without any extra annotations.

  • Disable Swagger annotation reliance
    To make sure Swagger/SpringFox doesn’t require Swagger annotations, configure it to ignore annotation-driven metadata and instead use the Javadocs (via the same parsed metadata Spring Auto REST Docs uses). You can do this by customizing the ModelBuilderPlugin:

    @Component
    public class JavadocModelPlugin implements ModelBuilderPlugin {
        // Use Spring Auto REST Docs' Javadoc parser to extract field descriptions
        private final JavadocReader javadocReader;
    
        // Constructor injection
    
        @Override
        public void apply(ModelContext context) {
            Class<?> modelClass = context.getType();
            Field[] fields = modelClass.getDeclaredFields();
            for (Field field : fields) {
                String description = javadocReader.getFieldDescription(modelClass, field.getName());
                if (description != null) {
                    context.builder().property(field.getName(), Property.builder()
                        .description(description)
                        .build());
                }
            }
        }
    
        @Override
        public boolean supports(DocumentationType delimiter) {
            return DocumentationType.SWAGGER_2.equals(delimiter);
        }
    }
    

Final Notes on Integration

  • Version Compatibility: Ensure you’re using compatible versions: Spring Auto REST Docs 2.x works with Spring Boot 2.x, SpringFox 2.9.x/3.x, and swagger2markup 1.3.x.
  • swagger2markup Integration: swagger2markup can still generate static docs (Asciidoc, HTML, PDF) from the Swagger API metadata that now uses your Javadocs and test-generated examples—just point it to your Swagger endpoint as usual.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:44:26