其他網址
swagger 介紹及兩種使用方法_程序猿-HZQ-CSDN博客_swagger
Spring Boot中使用Swagger2構建強大的RESTful API文檔 - 簡書
方案1:swagger-spring-boot-starter
其他網址
GitHub - SpringForAll/spring-boot-starter-swagger(github:有詳細教程)
本處配置一個最小工程的示例,詳細配置和其他功能見上邊的github網址。具體用法和下邊的“方案2:使用官方依賴”一樣。
1.引入依賴
第三方swagger依賴
<dependency> <groupId>com.spring4all</groupId> <artifactId>swagger-spring-boot-starter</artifactId> <version>1.7.0.RELEASE</version> </dependency>
2.使能swagger
在Spring Boot項目的啓動類上添加@EnableSwagger2Doc註解。
@EnableSwagger2Doc @SpringBootApplication public class MyApplication{ public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
此時就能產生所有當前Spring MVC加載的請求映射文檔。
方案2:官方依賴(優化版)
1.依賴及配置(優化版)
引入依賴
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
第一個是API獲取的包,第二是官方給出的一個ui界面。這個界面可以自定義,默認是官方的,對於安全問題,以及ui路由設置需要着重思考。
配置swagger
Swagger2Config.java
一定注意“RequestHandlerSelectors.basePackage”要填寫正確
package com.example.demo.conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2
//在生產環境不開啓,此方式有問題,待查找資料解決,故用下面設置布爾值來實現安全控制
//@Profile({"dev", "test"})
public class Swagger2Config {
private boolean swaggerShow = true;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(swaggerShow)
.groupName("demo.controller1(groupName)")
//.globalOperationParameters(getTocken())
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
// 可以爲多個包添加接口說明。(@Bean的方法名是任意的)
// 實際開發中,groupName與RequestHandlerSelectors.basePackage應一一對應。(本處爲簡潔用了同一個)
@Bean
public Docket createRestApi2() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(swaggerShow)
.groupName("demo.controller2(groupName)")
//.globalOperationParameters(getTocken())
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger的Demo(title)")
.description("Swagger的Demo(description)")
//下邊這行可以直接註釋掉
.termsOfServiceUrl("https://blog.csdn.net/feiying0canglang/")
.contact("Swagger的Demo(contact)")
.version("Swagger的Demo(version)")
.build();
}
// public List getTocken() {
// List<Parameter> list = new ArrayList<>();
// ParameterBuilder tocken = new ParameterBuilder()
// .name("Authorization")
// .description("認證信息")
// .modelRef(new ModelRef("string"))
// .parameterType("header")
// .required(true);
// list.add(tocken.build());
//
// return list;
// }
}
如上代碼所示,
- 通過@Configuration註解,讓Spring來加載該類配置。
- 再通過@EnableSwagger2註解來啓用Swagger2。
- 再通過createRestApi函數創建Docket的Bean之後,apiInfo()用來創建該Api的基本信息(這些基本信息會展現在文檔頁面中)。
- select()函數返回一個ApiSelectorBuilder實例用來控制哪些接口暴露給Swagger來展現,本例採用指定掃描的包路徑來定義,Swagger會掃描該包下所有Controller定義的API,併產生文檔內容(除了被@ApiIgnore指定的請求)。
2.編寫代碼(優化版)
上邊Controller的方法不是很多,但很多方法都要用@ApiImplicitParam進行註解。如果方法增多,而大部分方法都是與User類有關的,那麼有沒有什麼辦法優化呢?
答案是:有。可以把User類以及其字段進行註解,這樣在Controller中就不用對大部分方法使用@ApiImplicitParam了。
User.java
package com.example.demo.bean;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Component;
@ApiModel(value = "用戶詳細實體user(value)", description = "用戶id,名字,年齡(description)")
@Component
public class User {
@ApiModelProperty(name = "id(name)", value = "用戶ID(value)", required = true, dataType = "Long")
private Long id;
private String name;
private Long age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}
}
UserController.java
package com.example.demo.controller;
import com.example.demo.bean.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import java.util.*;
//下邊這行可以不寫。若不寫,默認名字爲:"user controller"
@Api( value = "用戶管理控制器(value)",
tags = {"用戶控制器a(tags)", "用戶控制器b(tags)"},
)
@RestController
@RequestMapping(value="/users") // 通過這裏配置使下面的映射都在/users下,可去除
public class UserController {
static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());
@ApiOperation(value="獲取用戶列表", notes="")
@RequestMapping(value={""}, method=RequestMethod.GET)
public List<User> getUserList() {
List<User> r = new ArrayList<User>(users.values());
return r;
}
@ApiOperation(value="創建用戶", notes="根據User對象創建用戶")
//@ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User")
@RequestMapping(value="", method=RequestMethod.POST)
public String postUser(@RequestBody User user) {
users.put(user.getId(), user);
return "success";
}
@ApiOperation(value="獲取用戶詳細信息", notes="根據url的id來獲取用戶詳細信息")
//@ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long")
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public User getUser(@PathVariable Long id) {
return users.get(id);
}
@ApiOperation(value="更新用戶詳細信息", notes="根據url的id指定更新對象,並根據傳來的user信息更新用戶詳細信息")
// @ApiImplicitParams({
// @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long"),
// @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User")
// })
@RequestMapping(value="/{id}", method=RequestMethod.PUT)
public String putUser(@PathVariable Long id, @RequestBody User user) {
User u = users.get(id);
u.setName(user.getName());
u.setAge(user.getAge());
users.put(id, u);
return "success";
}
@ApiOperation(value="刪除用戶", notes="根據url的id來指定刪除對象")
// @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long")
@RequestMapping(value="/{id}", method= RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id) {
users.remove(id);
return "success";
}
@ApiOperation(value="刪除所有用戶", notes="")
@RequestMapping(value="", method= RequestMethod.DELETE)
public String deleteAllUser() {
users.clear();
return "success";
}
}
3.文檔查看測試(優化版)
運行項目。成功後訪問:http://localhost:8080/swagger-ui.html
可得到此頁面
4.接口實際測試
Swagger不僅可以提供接口查看,還可以直接測試。
接上文。點擊“創建用戶”
點擊“Try it out”
點擊完之後出現以下界面。箭頭所指的數字和字符串等是可以更改的,本處進行修改。改完後點擊最下方“Execute”
即出現成功響應
同樣的操作,操作“獲取用戶列表” ,結果如下
方案2:官方依賴(基礎版)
整個工程的結構
1.依賴及配置(基礎版)
引入依賴
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
第一個是API獲取的包,第二是官方給出的一個ui界面。這個界面可以自定義,默認是官方的,對於安全問題,以及ui路由設置需要着重思考。
配置swagger
Swagger2Config.java
一定注意“RequestHandlerSelectors.basePackage”要填寫正確
package com.example.demo.conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
// .groupName("com.example(groupName)")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.any())
.build();
}
// 可以爲多個包添加接口說明。(@Bean的方法名是任意的)
// @Bean
// public Docket createRestApi2() {
// return new Docket(DocumentationType.SWAGGER_2)
// .apiInfo(apiInfo())
// .select()
// .apis(RequestHandlerSelectors.basePackage("com.example.test"))
// .paths(PathSelectors.any())
// .build();
// }
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger的Demo(title)")
.description("Swagger的Demo(description)")
//下邊這行可以直接註釋掉
.termsOfServiceUrl("https://blog.csdn.net/feiying0canglang/")
.contact("Swagger的Demo(contact)")
.version("Swagger的Demo(version)")
.build();
}
}
如上代碼所示,
- 通過@Configuration註解,讓Spring來加載該類配置。
- 再通過@EnableSwagger2註解來啓用Swagger2。
- 再通過createRestApi函數創建Docket的Bean之後,apiInfo()用來創建該Api的基本信息(這些基本信息會展現在文檔頁面中)。
- select()函數返回一個ApiSelectorBuilder實例用來控制哪些接口暴露給Swagger來展現,本例採用指定掃描的包路徑來定義,Swagger會掃描該包下所有Controller定義的API,併產生文檔內容(除了被@ApiIgnore指定的請求)。
2.編寫代碼(基礎版)
User.java
package com.example.demo.bean;
import org.springframework.stereotype.Component;
@Component
public class User {
private Long id;
private String name;
private Long age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}
}
UserController.java
package com.example.demo.controller;
import com.example.demo.bean.User;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import java.util.*;
//下邊這行可以不寫。若不寫,默認名字爲:"user controller"
//@Api(value="用戶管理類", notes="")
@RestController
@RequestMapping(value="/users") // 通過這裏配置使下面的映射都在/users下,可去除
public class UserController {
static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());
@ApiOperation(value="獲取用戶列表", notes="")
@RequestMapping(value={""}, method=RequestMethod.GET)
public List<User> getUserList() {
List<User> r = new ArrayList<User>(users.values());
return r;
}
@ApiOperation(value="創建用戶", notes="根據User對象創建用戶")
@ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User")
@RequestMapping(value="", method=RequestMethod.POST)
public String postUser(@RequestBody User user) {
users.put(user.getId(), user);
return "success";
}
@ApiOperation(value="獲取用戶詳細信息", notes="根據url的id來獲取用戶詳細信息")
@ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long")
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public User getUser(@PathVariable Long id) {
return users.get(id);
}
@ApiOperation(value="更新用戶詳細信息", notes="根據url的id指定更新對象,並根據傳來的user信息更新用戶詳細信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long"),
@ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User")
})
@RequestMapping(value="/{id}", method=RequestMethod.PUT)
public String putUser(@PathVariable Long id, @RequestBody User user) {
User u = users.get(id);
u.setName(user.getName());
u.setAge(user.getAge());
users.put(id, u);
return "success";
}
@ApiOperation(value="刪除用戶", notes="根據url的id來指定刪除對象")
@ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long")
@RequestMapping(value="/{id}", method= RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id) {
users.remove(id);
return "success";
}
@ApiOperation(value="刪除所有用戶", notes="")
@RequestMapping(value="", method= RequestMethod.DELETE)
public String deleteAllUser() {
users.clear();
return "success";
}
}
3.文檔查看測試(基礎版)
運行項目。成功後訪問:http://localhost:8080/swagger-ui.html
可得到此頁面
點擊“http://localhost:8080/v2/api-docs”可以得到如下圖片
(我用的是火狐瀏覽器,它自動解析JSON,若是360極速瀏覽器則沒這個效果)
點擊“Terms of service”可以跳轉到我們指定的網址,本處是“https://blog.csdn.net/feiying0canglang/”
點擊“User Controller”