Swagger 初体验

本贴最后更新于 1893 天前,其中的信息可能已经东海扬尘

这世间 没有 不相交的平行线

前言

以前刚接触到 Swagger,不知道他还能导出成 Word、PDF 文档,就觉得 Postman+ 文档够用了,现在觉得代码中集成这样的框架,在初期能够方便很多。

  • 功能丰富 :支持多种注解,自动生成接口文档界面,支持在界面测试 API 接口功能;
  • 条理清晰 :开发过程中花一点写注释的时间,就可以及时的更新 API 文档,省心省力;
  • 整合简单 :通过添加 pom 依赖和简单配置,内嵌于应用中就可同时发布 API 接口文档界面,不需要部署独立服务。

Swagger 集成项目

Swagger 本身是一种规范,而 SpringFox-Swagger 是专注于 Spring 生态的实现,Spring-Swagger-UI 则是对 Swagger-UI 的封装。

代码整整合也非常的简单,首先是 pom 引入:

pom 引入

<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> <dependency> <groupId>io.github.swagger2markup</groupId> <artifactId>swagger2markup</artifactId> <version>1.3.1</version> </dependency>

其中 swagger2markup 是用于 Swagger 导出 PDF/HTML 的依赖,离线文档之后再更新,目前还有点问题。

application.properties 中加这么一句 spring.resources.static-locations=classpath:/static/ ,不然 swagger-ui.html 这个页面会被拦截。

Configuration 注入

/** * @ClassName SwaggerConfiguration * @Description TODO * @Author MatthewHan * @Date 2019/7/16 16:15 * @Version 1.0 **/ @Configuration public class SwaggerConfiguration { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() // 这是注意的代码 .apis(RequestHandlerSelectors.basePackage("com.zrtg.ldapsync.common.action")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("ldap-sync接口文档") .description("用于大院LDAP服务器同步无纸化办公组织架构") .termsOfServiceUrl("http://gitlab.zrtg.com/996team/ldap-sync") .version("1.0") .build(); } }
  • 其中 basePackage 中的一般配置 controller 的路径, paths 属性进行过滤, apis 属性可以设置扫描包,或者通过注解的方式标识;通过 enable 属性,可以在 application-{profile}.properties 文件中设置相应值,主要用于控制生产环境不生成接口文档。另外还有 groupName() 进行分组,比如高级客户、~~低端人口(雾)~~之类的分组。
  • apiInfo 中包装了文档的 titledescriptionversion 这些信息。

然后在 SpringBoot 的入口类中加上 @EnableSwagger2 表示开启 Swagger2。

完成这些步骤后,发现其实访问 https://localhost/swagger-ui.html 并没有 swagger 页面,原因是在所映射的地址在 SpringBoot 静态资源文件夹下找不到。所以需要定义一个拦截器来放行。

实现 WebMvcConfigurer

/** * @ClassName WebMvcConfiguration * @Description 用于Swagger UI显示 * @Author MatthewHan * @Date 2019/7/16 16:37 * @Version 1.0 **/ @Configuration public class WebMvcConfiguration implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/templates/**") .addResourceLocations("classpath:/META-INF/resources/templates/"); } }

我们只需要重写 addResourceHandlers 方法即可,通过 addResourceHandler 添加映射路径,然后再通过 addResourceLocations 来指定路径。 addResourceLocations 指的是文件放置的目录, addResoureHandler 指的是对外暴露的访问路径。

在 controller 中集成注解

注解 描述
@Api 修饰整个类,描述 Controller 的作用
@ApiOperation 描述一个类的一个方法,或者说一个接口
@ApiParam 单个参数描述
@ApiModel 用对象来接收参数
@ApiProperty 用对象接收参数时,描述对象的一个字段
@ApiResponse HTTP 响应其中 1 个描述
@ApiResponses HTTP 响应整体描述
@ApiIgnore 使用该注解忽略这个 API
@ApiError 发生错误返回的信息
@ApiImplicitParam 一个请求参数
@ApiImplicitParams 多个请求参数

最后通过浏览器来访问 https://localhost/swagger-ui.html 如下图:

Swagger-UI

Method 类型、相关描述、Example、StatusCode 都会自动帮你生成。

小问题记录

注解问题

直接在通过 @PathVariable 注解的参数在 Swagger 中用了 @ApiImplicitParam ,发现在页面中请求是有问题的,这个注解应该对应的是 func(@Param("arg") String arg) 方法,实际上正确的用法是 @ApiParam 。类似下图代码:

/** * 测试 * 用于添加一个ou,例如:department,employee * @param ou * @return */ @ApiOperation(value = "添加一个OU") @ApiParam(name = "ou", value = "组织单元", required = true) @PostMapping("/add-ldap-ou/{ou}") public BaseResult<String> addLdapOu(@PathVariable("ou")String ou){ ... }

与 Shiro 集成的问题

通过无拦截测试总结了如下的资源路径是 swagger 在渲染页面时的必需。如果工程中包含了 Shiro 安全框架,需要对 swagger 进行放行。

// 设置拦截器 Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); // swagger放行 filterChainDefinitionMap.put("/swagger-ui.html", "anon"); filterChainDefinitionMap.put("/swagger-resources/**", "anon"); filterChainDefinitionMap.put("/v2/**", "anon"); filterChainDefinitionMap.put("/webjars/**", "anon"); filterChainDefinitionMap.put("/configuration/**", "anon"); ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

在你的 Shiro 配置类中添加如上路径即可。

离线文档(后续更新)

  • Swagger

    Swagger 是一款非常流行的 API 开发工具,它遵循 OpenAPI Specification(这是一种通用的、和编程语言无关的 API 描述规范)。Swagger 贯穿整个 API 生命周期,如 API 的设计、编写文档、测试和部署。

    26 引用 • 35 回帖 • 3 关注
  • 文档
    56 引用 • 1289 回帖 • 2 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...