微服务中整合Swagger2接口框架

        在SpringCloud+SpringBoot微服务架构开发模式中,我们通常使用前后端分离的方式进行开发。前后端分离的方式使得接口数据成为前端开发人员与后端开发人员的沟通一种必要方式。Swagger ui 是一个API在线文档生成和测试的利器,在某种程度上可以媲美postman。作为后端开发人员来说可能会更倾向于使用postman来调试接口,但是作为前端人员了解后台接口数据,Swagger无意是更好的选择。   

         一、如何在SpringCloud+SpringBoot微服务中整合Swagger2框架

          1.maven引入下面的依赖包:    

           <!-- Swagger2强大RESTful API文档 -->
           <dependency>
               <groupId>io.springfox</groupId>
               <artifactId>springfox-swagger2</artifactId>
               <version>2.6.1</version>
           </dependency>
           <dependency>
               <groupId>io.springfox</groupId>
               <artifactId>springfox-swagger-ui</artifactId>
               <version>2.6.1</version>
           </dependency>

           2.在webconfig.java(Swagger类)文件中,给Webconfig加上@EnableSwagger2注解,在该类中添加如下方法:

          @Value(value = "${swagger.enabled}")
          oolean swaggerEnabled;
          @Bean
          public Docket createRestApi() {
             return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                .enable(swaggerEnabled).select()
                .apis(RequestHandlerSelectors.basePackage("cn.tolus.survey.controller")).paths(PathSelectors.any())
                .build();
          }

          private ApiInfo apiInfo() {
              return new ApiInfoBuilder().title("调查问卷平台").description("调查问卷接口说明")
                 .termsOfServiceUrl("http://www.tolus.cn").contact("WuZhengJun").version("1.0").build();
          }

            3.在微服务的config文件中加入Swagger开关:

                  微服务中整合Swagger2接口框架

             4.给控制器和方法加上描述注解,Swagger自动把描述加载到页面

                 (1)controller描述

                            @Api(description = "问卷控制器")

                 (2)方法描述

                           @ApiOperation(value = "导出问卷统计结果")

                  (3)参数描述,多个参数用@ApiImplicitParams( @ApiImplicitParam(name="",value = "",dataType = "") )

                          @ApiImplicitParam(name = "naireId",value = "问卷id",dataType = "String")

             5.配置完成,访问API接口页面

                  http://localhost:9002/swagger-ui.html

        二、如何使用Swagger2查看API

             1.浏览器输入地址:http://localhost:9002/swagger-ui.html 

微服务中整合Swagger2接口框架

          2.在select a spec处选择一个服务模块,就可看到该模块下所有控制接口

微服务中整合Swagger2接口框架

           3.展开某一个controller,便可看到该controller下的所有方法

微服务中整合Swagger2接口框架

          4.点击方法,可看到该方法参数,还可以try IT out测试接口方法,查看返回数据

微服务中整合Swagger2接口框架

微服务中整合Swagger2接口框架