How set SpringFox to show two (or more) versions of the Rest API using Spring Boot?

馋奶兔 提交于 2019-12-08 18:30:34

It's very simple. Just create one Docket for each version.

Example, the first version:

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

And for version two:

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

The secret here is filter the available endpoints by the produces attribute.

The Swagger-UI will show the two versions on the combo:

This code needs to be on a class annotated with @Configuration. You also need to enable the Swagger with @EnableSwagger2.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!