Swagger Core v3在Java中的实现

时间:2019-06-05 10:37:54

标签: java swagger swagger-3.0

我正在编写一些API,并且想在编写代码时集成文档,因此我发现Swagger是实现此目的的一种好方法。

我使用了Swagger核心v3表示法,所以我的类类似于:

@RestController

@RequestMapping("/api/v1/bundles")

@OpenAPIDefinition(

        info = @Info(
                title = "Lifecycle Management RESTful API.",
                version = "1",
                description = "TODO",
                license = @License(name = "Apache 2.0", url = "xxx"),
                contact = @Contact(url = "xxx", name = "xx", email = "xxx@xxx.fr")
        ))

public class RestBundle {

    @GetMapping(value = "/{nodeId}",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    @Operation(summary = "Get all bundles",
            description = "Get all available bundles status from a specific node")
    public Something(..)  {
        //Something ...
    }

}

然后我创建一个配置类:

@Configuration
@EnableSwagger2

public class SwaggerConfig {


    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }


    ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("ANF Orchestrator")
                .description("REST API for ANF Orchestrator")
                .license("Apache 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
                .termsOfServiceUrl("")
                .version("1.0.0")
                .contact(new Contact("Amine","xxx", "aalaouie@laas.fr"))
                .build();
    }
}

我想启用Swagger的UI来获取文档,但是当我输入以下内容时:   ... / swagger-ui.html

我得到:

  

无法呈现此定义   提供的定义未指定有效的版本字段。

     

请指明有效的Swagger或OpenAPI版本字段。支持的版本字段包括:“ 2.0”和与openapi匹配的版本:3.0.n(例如,openapi:3.0.0)。

2 个答案:

答案 0 :(得分:0)

尝试使用 WebMvcConfigurationSupport 扩展 SwaggerConfig 类,并使用如下实现覆盖其名为 addResourceHandlers 的方法:

@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");
    registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

答案 1 :(得分:0)

在课堂上,您可以尝试删除此注释吗,因为SwaggerConfig已包含Docket信息。

  @OpenAPIDefinition(

            info = @Info(
                    title = "Lifecycle Management RESTful API.",
                    version = "1",
                    description = "TODO",
                    license = @License(name = "Apache 2.0", url = "xxx"),
                    contact = @Contact(url = "xxx", name = "xx", email = "xxx@xxx.fr")
            ))