简体   繁体   English

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

[英]How to pass file content to swagger @ExampleProperty annotation value?

I am using swagger 3.0.0-Snapshot to create documentation for my Spring Boot application. 我正在使用swagger 3.0.0-Snapshot为我的Spring Boot应用程序创建文档。 My maven dependencies are 我的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>

My swagger config class is as simple as possible: 我的大张旗鼓的配置类是尽可能简单的:

@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);
    }

And my controller method has the following annotation: 我的控制器方法具有以下注释:

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

It is working and shows in Swagger UI "Example Value" field value that has constant string exampleValue that is private static String. 它正在运行,并在Swagger UI中显示了具有常量字符串exampleValue的字段“ Example Value”字段值,该字符串是私有静态String。

The question is how to pass the content of json file that is in resources folder to @ExampleProperty value? 问题是如何将资源文件夹中json文件的内容传递给@ExampleProperty值?

I tried to read file content in static block and pass it to initialize final String with it, but then the compiler says that "Attribute value has to be constant". 我试图读取静态块中的文件内容,并将其传递给它初始化最终的String,但是随后编译器说“属性值必须恒定”。

The content of json file must be shown in example field in Swagger UI. json文件的内容必须在Swagger UI的示例字段中显示。

Good news is that Swagger is using Spring and it is possible to use the power of DI. 好消息是Swagger正在使用Spring,并且可以使用DI的功能。

For instance, you want to add new functionality to ServiceModelToSwagger2MapperImpl. 例如,您想向ServiceModelToSwagger2MapperImpl添加新功能。 Create your own component that extends it and mark it primary. 创建自己的扩展组件并将其标记为主要。 Spring will autowire your implementation of ServiceModelToSwagger2Mapper abstract class. Spring将自动连接ServiceModelToSwagger2Mapper抽象类的实现。

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

For instance, you want it to read the content of the file and put it to the example field: 例如,您希望它读取文件的内容并将其放在示例字段中:

@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;
}

And here is an example of usage in your controller: 这是控制器中用法的示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM