springboot整合swagger及日常使用

痛点:经常性修改接口导致接口文档也经常需要同步修改,而这是一件很沉重的工作,非常浪费开发人员的时间,这时候我们找到了好伙伴,swagger。

1:引入POM

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

2:配置swagger

@Configuration
@EnableSwagger2
public class SwaggerConfig {

  @Bean
  public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.*.*"))
        .paths(PathSelectors.any())
        .build();
  }

  public ApiInfo apiInfo() {
    return new ApiInfoBuilder().title("*****接口文档")
        .description("将于12月25日圣诞节上线")
        .contact(new Contact("ZXc", "", "[email protected]"))
        .version("1.0")
        .build();
  }

}

3:文档编写示例

@Controller
@RequestMapping("/随便")
@Api(value = "随便起", description = "相关接口")
public class 某某Controller  {

  @GetMapping("/list/{category}")
  @ResponseMessage
  @ApiOperation(value = "通过分类获取分页集合", notes =
      "根据列表啦啦啦")
  public Page<abc> listByCategory(
      @ApiParam(value = "1:人工智能 2:云计算/大数据 3:区块链 4:数据库 "
          + "5:程序人生 6:游戏开发 7:研发管理 8:前端 9:移动开发 "
          + "10:物联网 11:运维 12:计算机基础 13:编程语言 14:架构"
          + " 15:音视频开发 16:安全 99:其他 ") 
          @PathVariable(value = "category") String category) {

    return 某某Service.listByCategory(category);
  }
}

4:遇到的问题

有的童鞋可能会在自定义配置springmvc,这样会导致http://localhost:8088/swagger-ui.html这个UI界面报 swagger-ui.html 的no mapping,这是因为资源映射不到的原因,我们需要在自定义的springmvc中找到模版方法然后添加映射,如下

@Override
  protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
        .addResourceLocations("classpath:/META-INF/resources/");
    registry.addResourceHandler("/webjars/**")
        .addResourceLocations("classpath:/META-INF/resources/webjars/");
  }

至此,你就可以访问http://localhost:你的端口/swagger-ui.html 来观看你的文档了。

猜你喜欢

转载自blog.csdn.net/weixin_39781526/article/details/85003065