spring cloud集成swagger

2020年02月05日 163点热度 0人点赞 0条评论

如果是聚合项目的话,可以在dependencyManagement里指定版本号,方便管理

            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>2.9.2</version>
            </dependency>
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>2.9.2</version>
            </dependency>

zuul网关

zuul网关这儿可以将所有微服务的文档集成起来,方便使用

添加依赖

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
        </dependency>

添加配置类

@Configuration
@EnableSwagger2
@Primary
public class SwaggerConfig  implements SwaggerResourcesProvider {

    private final RouteLocator routeLocator;

    public SwaggerConfig(RouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

    @Override
    public List<SwaggerResource> get() {
        List resources = new ArrayList();
        List<Route> routes = routeLocator.getRoutes();
        routes.forEach( route -> {
            resources.add(swaggerResource(route.getId(), route.getFullPath().replace("**", "v2/api-docs"),"2.0"));
        });
        return resources;
    }

    private SwaggerResource swaggerResource(String name, String location, String version) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }
}

微服务

添加依赖

微服务这儿无需添加界面的依赖

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
        </dependency>

配置类

@EnableSwagger2
@Configuration
public class SwaggerConfig {
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.likole.×××.×××.controller"))
                .paths(PathSelectors.any())
                .build();

    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("标题")
                .contact(new Contact("名字", "网址", "邮箱"))
                .version("版本号")
                .description("描述")
                .build();
    }
}

具体用法略

最后访问swagger-ui.html即可,无需加prefix

参考文章:https://blog.csdn.net/kinghmj01/article/details/90902271

likole

人能常清静,天地悉皆归

文章评论