最近 SpringFox 3.0.0 发布了,距离上一次大版本2.9.2足足有2年多时间了。可能看到这个名字,不少读者会有点陌生。可是,只要给你们看一下这两个依赖,你就知道了!html
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>3.0.0</version> <scope>compile</scope> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>3.0.0</version> <scope>compile</scope> </dependency>
当咱们在使用Spring MVC写接口的时候,为了生成API文档,为了方便整合Swagger,都是用这个SpringFox的这套封装。可是,自从2.9.2版本更新以后,就一直没有什么动静,也没有更上Spring Boot的大潮流,有一段时间还一直都是写个配置类来为项目添加文档配置的。为此,以前就造了这么个轮子:java
也没什么难度,就是造的早,因此获得了很多Star。如今SpringFox出了一个starter,看了一下功能,虽然还不完美,但相较于以前咱们本身的轮子来讲仍是好蛮多的。来看看这个版本有些什么亮点:git
对于此次的更新,我以为比较突出的几点:Webflux的支持,目前的轮子就没有作到;对OpenApi 3的支持;以及对Swagger 2的兼容(能够比较方便的作升级了)。github
说那么多,不如来一发程序实验下更直接!spring
第一步:建立一个Spring Boot项目,这里不展开,不会的看之前的教程:快速入门api
第二步:pom.xml
中添加依赖:app
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> <dependency>
如今简洁了很多,一个依赖搞定!spring-boot
第三步:应用主类增长注解@EnableOpenApi
。学习
@EnableOpenApi @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
第四步:配置一些接口例子,好比:ui
@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; @NotNull private 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
注意:
- 此次更新,移除了原来默认的swagger页面路径:
http://host/context-path/swagger-ui.html
,新增了两个可访问路径:http://host/context-path/swagger-ui/index.html
和http://host/context-path/swagger-ui/
- 经过调整日志级别,还能够看到新版本的swagger文档接口也有新增,除了之前老版本的文档接口
/v2/api-docs
以外,还多了一个新版本的/v3/api-docs
接口。
本系列教程《Spring Boot 2.x基础教程》点击直达!
本文的相关例子能够查看下面仓库中的chapter2-7
目录:
若是您以为本文不错,欢迎Star
支持,您的关注是我坚持的动力!
本文首发: 尝鲜刚发布的 SpringFox 3.0.0,之前造的轮子能够不用了...,转载请注明出处。
欢迎关注个人公众号:程序猿DD,得到独家整理的学习资源和平常干货推送。 点击直达本系列教程目录。