本文共 6138 字,大约阅读时间需要 20 分钟。
目录
在团队开发中,一个好的 API 文档不但可以减少大量的沟通成本,还可以帮助一位新人快速上手业务。传统的做法是由开发人员创建一份 RESTful API 文档来记录所有的接口细节,并在程序员之间代代相传。
这种做法存在以下几个问题:
API 接口众多,细节复杂,需要考虑不同的HTTP请求类型、HTTP头部信息、HTTP请求内容等,想要高质量的完成这份文档需要耗费大量的精力;
难以维护。随着需求的变更和项目的优化、推进,接口的细节在不断地演变,接口描述文档也需要同步修订,可是文档和代码处于两个不同的媒介,除非有严格的管理机制,否则很容易出现文档、接口不一致的情况
Swagger2 的出现就是为了从根本上解决上述问题。它作为一个规范和完整的框架,可以用于生成、描述、调用和可视化 RESTful 风格的 Web 服务:
接口文档在线自动生成,文档随接口变动实时更新,节省维护成本
支持在线接口测试,不依赖第三方工具
... io.springfox springfox-swagger-ui 2.9.2 io.springfox springfox-swagger2 2.9.2
Swagger2 的配置也是比较容易的,在项目创建成功之后,只需要开发者自己提供一个 Docket 的 Bean 即可,如下:
@Configuration@EnableSwagger2public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .pathMapping("/") .select() .apis(RequestHandlerSelectors.basePackage("org.javaboy.controller")) .paths(PathSelectors.any()) .build().apiInfo(new ApiInfoBuilder() .title("SpringBoot整合Swagger") .description("SpringBoot整合Swagger,详细信息......") .version("9.0") .contact(new Contact("test","blog.csdn.net","test@gmail.com")) .license("The Apache License") .licenseUrl("http://www.test.org") .build()); }}
这里提供一个配置类,首先通过 @EnableSwagger2 注解启用 Swagger2 ,然后配置一个 Docket Bean,这个 Bean 中,配置映射路径和要扫描的接口的位置,在 apiInfo 中,主要配置一下 Swagger2 文档网站的信息,例如网站的 title,网站的描述,联系人的信息,使用的协议等等。
如此,Swagger2 就算配置成功了,非常方便。
此时启动项目,输入 http://localhost:8080/swagger-ui.html,能够看到如下页面,说明已经配置成功了:
接下来就是创建接口了
@RestController@Api(tags = "用户管理相关接口")@RequestMapping("/user")public class UserController { @PostMapping("/") @ApiOperation("添加用户的接口") @ApiImplicitParams({ @ApiImplicitParam(name = "username", value = "用户名", defaultValue = "李四"), @ApiImplicitParam(name = "address", value = "用户地址", defaultValue = "深圳", required = true) }) public RespBean addUser(String username, @RequestParam(required = true) String address) { return new RespBean(); } @GetMapping("/") @ApiOperation("根据id查询用户的接口") @ApiImplicitParam(name = "id", value = "用户id", defaultValue = "99", required = true) public User getUserById(@PathVariable Integer id) { User user = new User(); user.setId(id); return user; } @PutMapping("/{id}") @ApiOperation("根据id更新用户的接口") public User updateUserById(@RequestBody User user) { return user; }}
注解说明:
@Api 注解可以用来标记当前 Controller 的功能。
@ApiOperation 注解用来标记一个方法的作用。 @ApiImplicitParam 注解用来描述一个参数,可以配置参数的中文含义,也可以给参数设置默认值,这样在接口测试的时候可以避免手动输入。 如果有多个参数,则需要使用多个 @ApiImplicitParam 注解来描述,多个 @ApiImplicitParam 注解需要放在一个 @ApiImplicitParams 注解中。 需要注意的是,@ApiImplicitParam 注解中虽然可以指定参数是必填的,但是却不能代替 @RequestParam(required = true) ,前者的必填只是在 Swagger2 框架内必填,抛弃了 Swagger2 ,这个限制就没用了,所以假如开发者需要指定一个参数必填, @RequestParam(required = true) 注解还是不能省略。 如果参数是一个对象(例如上文的更新接口),对于参数的描述也可以放在实体类中。例如下面一段代码:@ApiModelpublic class User { @ApiModelProperty(value = "用户id") private Integer id; @ApiModelProperty(value = "用户名") private String username; @ApiModelProperty(value = "用户地址") private String address; //getter/setter}
刷新刚刚打开的页面,可以看到如下效果:
可以看到,所有的接口这里都列出来了,包括接口请求方式,接口地址以及接口的名字等
这两个,一个用来生成接口文档(JSON 数据),另一个用来展示将 JSON 可视化。
io.springfox springfox-swagger2 2.9.2 io.springfox springfox-swagger-ui 2.9.2
在 3.0 版本中,我们不需要这么麻烦了,一个 starter 就可以搞定:
io.springfox springfox-boot-starter 3.0.0
和 Spring Boot 中的其他 starter 一样,springfox-boot-starter 依赖可以实现零配置以及自动配置支持。也就是说,如果你没有其他特殊需求,加一个这个依赖就行了,接口文档就自动生成了。
什么是 OpenAPI?
OpenAPI 规范其实就是以前的 Swagger 规范,它是一种 REST API 的描述格式,通过既定的规范来描述文档接口,它是业界真正的 API 文档标准,可以通过 YAML 或者 JSON 来描述。它包括如下内容:
关于 OpenAPI 的更多内容,感兴趣的小伙伴可以在 GitHub 上查看:
3.0 中的接口地址也和之前有所不同,以前在 2.9.2 中我们主要访问两个地址:
现在在 3.0 中,这两个地址也发生了变化:
特别是文档页面地址,如果用了 3.0,而去访问之前的页面,会报 404。
旧的注解还可以继续使用,不过在 3.0 中还提供了一些其他注解。
例如我们可以使用 @EnableOpenApi 代替以前旧版本中的 @EnableSwagger2。
但是实际使用中,@EnableOpenApi 注解的功能不明显,加不加都行。翻了下源码,@EnableOpenApi 注解主要功能是为了导入 OpenApiDocumentationConfiguration 配置类,如下:
123456 | @Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)@Target(value = {java.lang.annotation.ElementType.TYPE})@Documented@Import(OpenApiDocumentationConfiguration.class)public @interface EnableOpenApi {} |
自动化配置类 OpenApiAutoConfiguration,如下:
12345678910111213141516 | @Configuration@EnableConfigurationProperties(SpringfoxConfigurationProperties.class)@ConditionalOnProperty(value = "springfox.documentation.enabled", havingValue = "true", matchIfMissing = true)@Import({ OpenApiDocumentationConfiguration.class, SpringDataRestConfiguration.class, BeanValidatorPluginsConfiguration.class, Swagger2DocumentationConfiguration.class, SwaggerUiWebFluxConfiguration.class, SwaggerUiWebMvcConfiguration.class})@AutoConfigureAfter({ WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class })public class OpenApiAutoConfiguration {} |
可以看到,自动化配置类里边也导入了 OpenApiDocumentationConfiguration。
所以在正常情况下,实际上不需要添加 @EnableOpenApi 注解。
根据 OpenApiAutoConfiguration 上的 @ConditionalOnProperty 条件注解中的定义,我们发现,如果在 application.properties 中设置 springfox.documentation.enabled=false
,即关闭了 swagger 功能,此时自动化配置类就不执行了,这个时候可以通过 @EnableOpenApi 注解导入 OpenApiDocumentationConfiguration 配置类。技术上来说逻辑是这样,不过应用中暂未发现这样的需求(即在 application.properties 中关闭 swagger,再通过 @EnableOpenApi 注解开启)。
另外,以前我们用的 @ApiResponses/@ApiResponse 注解,在 3.0 中名字没变,但是所在的包变
另外,我们之前用的 @ApiOperation 注解在 3.0 中可以使用 @Operation 代替。
另外还有一些新注解如 @Parameter、Parameters、@Schema 等
参考地址: