如何将文件内容传递给 swagger @ExampleProperty 注释值?

How to pass file content to swagger @ExampleProperty annotation value?

我正在使用 swagger 3.0.0-Snapshot 为我的 Spring 引导应用程序创建文档。 我的 Maven 依赖项是

<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>3.0.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>3.0.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-spring-webmvc</artifactId>
            <version>3.0.0-SNAPSHOT</version>
        </dependency>

我的 swagger 配置 class 尽可能简单:

@Configuration
@EnableSwagger2WebMvc
public class SwaggerConfig {
    @Bean
    public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
                .useDefaultResponseMessages(false)
                .select()
         .apis(RequestHandlerSelectors.basePackage("com.mycompany.cs"))
                .paths(PathSelectors.any())
                .build()
                .pathMapping("/")
                .useDefaultResponseMessages(false);
    }

并且我的控制器方法具有以下注释:

@ApiOperation(value = "Hello world", httpMethod = "POST")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "OK",
                    examples = @Example(value = @ExampleProperty(mediaType = "application/json",
                            value = exampleValue)))
    })

它正在工作并在 Swagger 中显示 UI "Example Value" 具有常量字符串 exampleValue 的字段值,它是私有静态字符串。

问题是如何将资源文件夹中的 json 文件的内容传递给 @ExampleProperty 值?

我试图读取静态块中的文件内容并将其传递给初始化最终字符串,但编译器说 "Attribute value has to be constant".

json 文件的内容必须显示在 Swagger 的示例字段中 UI。

好消息是Swagger正在使用Spring并且可以使用DI的力量

例如,您想向 ServiceModelToSwagger2MapperImpl 添加新功能。创建您自己的组件来扩展它并将其标记为主要组件。 Spring 将自动装配您的 ServiceModelToSwagger2Mapper 抽象实现 class。

@Component
@Primary
@Slf4j
public class ServiceModelToSwagger2MapperExtensionImpl extends ServiceModelToSwagger2MapperImpl {

比如你想让它读取文件的内容并把它放到示例字段中:

@Override
protected Map<String, Response> mapResponseMessages(Set<ResponseMessage> from) {
    Map<String, Response> responses = super.mapResponseMessages(from);
    responses.forEach((key, response)-> {
        Map<String, Object> examples = response.getExamples();
        examples.entrySet().forEach(example -> {
            Object exampleObject = example.getValue();
            if (exampleObject instanceof String) {
                String exampleValue = (String) exampleObject;
                if (exampleValue.startsWith("file:")) {
                    String fileContent = readFileContent(exampleValue);
                    example.setValue(fileContent);
                }
            }});
    });

    return responses;
}

private String readFileContent(String example) {
    String fileContent = "";
    try {
        String fileName = example.replace("file:", "");
        File resource = new ClassPathResource(fileName).getFile();
        if(resource.exists()) {
            fileContent
                    = new String(Files.readAllBytes(resource.toPath()));
        }
    } catch (
            IOException e) {
        log.error("Cannot read swagger documentation from file {}", example);
    }
    return fileContent;
}

下面是您的控制器中的用法示例:

@ApiResponses(value = {
        @ApiResponse(code = 200, message = "OK",
                examples = @Example(value = @ExampleProperty(mediaType = "application/vnd.siren+json",
                        value = "file:/data/controller-responses/reponse.json")))
})