最近 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,得到獨家整理的學習資源和平常乾貨推送。 點擊直達本系列教程目錄。