当前位置: 代码迷 >> 综合 >> springfox-swagger2 3.0.0使用教程
  详细解决方案

springfox-swagger2 3.0.0使用教程

热度:72   发布时间:2024-03-08 21:50:42.0

最近 SpringFox 3.0.0 发布了,距离上一次大版本2.9.2足足有2年多时间了。可能看到这个名字,很多读者会有点陌生。但是,只要给大家看一下这两个依赖,你就知道了!

<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>3.0.0</version><scope>compile</scope>
</dependency>

当我们在使用Spring MVC写接口的时候,为了生成API文档,为了方便整合Swagger,都是用这个SpringFox的这套封装。但是,自从2.9.2版本更新之后,就一直没有什么动静,也没有更上Spring Boot的大潮流,有一段时间还一直都是写个配置类来为项目添加文档配置的。为此,之前就造了这么个轮子:

  • https://github.com/SpringForAll/spring-boot-starter-swagger

也没什么难度,就是造的早,所以得到了不少Star。现在SpringFox出了一个starter,看了一下功能,虽然还不完美,但相较于之前我们自己的轮子来说还是好蛮多的。来看看这个版本有些什么亮点:

  • Spring 5,Webflux 支持(仅请求映射支持,尚不支持功能端点)
  • Spring Integration 支持
  • Spring Boot 支持 springfox-boot-starter 依赖性(零配置,自动配置支持)
  • 具有自动完成功能的文档化配置属性
  • 更好的规范兼容性
  • 支持 OpenApi 3.0.3
  • 几乎零依赖性(唯一需要的库是 spring-plugin、pswagger-core)
  • 现有的 swagger2 注释将继续有效,并丰富 open API 3.0 规范

对于这次的更新,我觉得比较突出的几点:Webflux的支持,目前的轮子就没有做到;对OpenApi 3的支持;以及对Swagger 2的兼容(可以比较方便的做升级了)。

上手尝鲜

说那么多,不如来一发程序实验下更直接!

第一步:创建一个Spring Boot项目,这里不展开,不会的看以前的教程:快速入门

第二步pom.xml中添加依赖:

<dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version>
<dependency>

现在简洁了不少,一个依赖搞定!

第三步:应用主类增加注解@EnableOpenApi

@EnableOpenApi
@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}}

第四步:配置一些接口例子,比如:

@Api(tags="用户管理")
@RestController
public class UserController {@ApiOperation("创建用户")@PostMapping("/users")public User create(@RequestBody @Valid User user) {return user;}@ApiOperation("用户详情")@GetMapping("/users/{id}")public User findById(@PathVariable Long id) {return new User("bbb", 21, "上海", "aaa@bbb.com");}@ApiOperation("用户列表")@GetMapping("/users")public List<User> list(@ApiParam("查看第几页") @RequestParam int pageIndex,@ApiParam("每页多少条") @RequestParam int pageSize) {List<User> result = new ArrayList<>();result.add(new User("aaa", 50, "北京", "aaa@ccc.com"));result.add(new User("bbb", 21, "广州", "aaa@ddd.com"));return result;}@ApiIgnore@DeleteMapping("/users/{id}")public String deleteById(@PathVariable Long id) {return "delete user : " + id;}}@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel("用户基本信息")
public class User {@ApiModelProperty("姓名")@Size(max = 20)private String name;@ApiModelProperty("年龄")@Max(150)@Min(1)private Integer age;@NotNullprivate String address;@Pattern(regexp = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")private String email;}

第五步:启动应用!访问swagger页面:http://localhost:8080/swagger-ui/index.html

注意:

  1. 这次更新,移除了原来默认的swagger页面路径:http://host/context-path/swagger-ui.html,新增了两个可访问路径:http://host/context-path/swagger-ui/index.htmlhttp://host/context-path/swagger-ui/
  2. 通过调整日志级别,还可以看到新版本的swagger文档接口也有新增,除了以前老版本的文档接口/v2/api-docs之外,还多了一个新版本的/v3/api-docs接口。
  相关解决方案