如何使用Spring Boot设置SpringFox以显示Rest API的两个(或更多)版本?

Dhe*_*rik 1 spring swagger spring-boot springfox

我试图弄清楚如何使用Spring Fox管理两个(或更多)API端点版本。

要对API进行版本控制,我正在通过内容协商使用版本控制,也称为使用Accept标头的版本控制。使用标头信息分别控制每个端点的版本。例如,对于第一版,我使用属性produces

@Override
@PostMapping(
        produces = "application/vnd.company.v1+json")
public ResponseEntity<User> createUser(
Run Code Online (Sandbox Code Playgroud)

对于第二版,我使用:

@Override
@PostMapping(
        produces = "application/vnd.company.v2+json",
        consumes = "application/vnd.company.v2+json")
public ResponseEntity<User> createUserVersion2(
Run Code Online (Sandbox Code Playgroud)

我不使用consumes第一个(v1)版本,因此如果客户端仅application/json在通话中使用,则默认情况下将调用第一个版本。

我想在Swagger UI上显示两个版本。怎么做?

Dhe*_*rik 5

非常简单 只需为每个版本创建一个Docket。

示例,第一个版本:

@Bean
public Docket customImplementation(
        @Value("${springfox.documentation.info.title}") String title,
        @Value("${springfox.documentation.info.description}") String description) {

    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo(title, description, "1.0"))
            .groupName("v1")
            .useDefaultResponseMessages(false)
            .securitySchemes(newArrayList(apiKey()))
            .pathMapping("/api")
            .securityContexts(newArrayList(securityContext())).select()
            .apis(e -> Objects.requireNonNull(e).produces().parallelStream()
                    .anyMatch(p -> "application/vnd.company.v1+json".equals(p.toString())))
            .paths(PathSelectors.any())
            .build();
}
Run Code Online (Sandbox Code Playgroud)

对于第二版:

@Bean
public Docket customImplementationV2(
        @Value("${springfox.documentation.info.title}") String title,
        @Value("${springfox.documentation.info.description}") String description) {

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo(title, description, "2.0"))
                .groupName("v2")
                .select()
                .apis(e -> Objects.requireNonNull(e).produces()
                        .parallelStream()
                        .anyMatch(p -> "application/vnd.company.v2+json".equals(p.toString())))
                .build();
}
Run Code Online (Sandbox Code Playgroud)

这里的秘密是通过produces属性过滤可用的端点。

Swagger-UI将在组合上显示两个版本:

在此处输入图片说明

该代码必须位于注释的类上@Configuration。您还需要使用启用Swagger @EnableSwagger2