美文网首页
Spring Cloud 学习笔记 - No.6 通过 Swag

Spring Cloud 学习笔记 - No.6 通过 Swag

作者: 专职跑龙套 | 来源:发表于2018-07-17 17:20 被阅读43次

    请先阅读之前的内容:

    关于 Swagger2,参见 Swagger 学习笔记及与 Spring Boot 的整合

    为 eureka-consumer 服务构建 API 文档

    首先在 pom.xml 中添加如下依赖:

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

    随后创建一个 Swagger2 配置类,通过 @EnableSwagger2 注解来启用 Swagger2:

    @Configuration
    @EnableSwagger2
    public class Swagger2 {
    
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example"))
                    .paths(PathSelectors.any())
                    .build();
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("RESTful APIs in eureka-consumer")
                    .description("RESTful APIs in eureka-consumer")
                    .termsOfServiceUrl("http://127.0.0.1:3001")
                    .contact("Xiang Chen")
                    .version("1.0")
                    .build();
        }
    
    }
    

    我们也可以通过 @ApiOperation 注解来给API增加说明(但这不是必须的),例如:

    @ApiOperation(value="提供 1 + 2 的加法结果", notes="")
    @GetMapping("/consumer")
    public String consumer() {
        return consumerService.consumer();
    }
    

    最后,重启服务,访问 http://127.0.0.1:3001/swagger-ui.html 可以看到 Swagger UI API 文档:

    Swagger UI API 文档

    相关文章

      网友评论

          本文标题:Spring Cloud 学习笔记 - No.6 通过 Swag

          本文链接:https://www.haomeiwen.com/subject/yajgpftx.html