簡介
前後端分離開發模式中,api文檔是最好的溝通方式。
Swagger
是一個規範和完整的框架,用於生成、描述、調用和可視化RESTful
風格的 Web 服務
。
1、及時性 (接口變更後,能夠及時準確地通知相關前後端開發人員)
2、規範性 (並且保證接口的規範性,如接口的地址,請求方式,參數及響應格式和錯誤信息)
3、一致性 (接口信息一致,不會出現因開發人員拿到的文檔版本不一致,而出現分歧)
4、可測性 (直接在接口文檔上進行測試,以方便理解業務),這個功能我覺得比Postman好用
一、引入Swagger相關依賴
<dependencies>
<!-- Swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<!-- Swagger-ui.html -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
二、創建配置文件
@Configuration
@EnableSwagger2
public class Swagger2Config {
// API接口包掃描的路徑
public static final String SWAGGER2_SCAN_PACKAGE = "top.liuchengyin.swagger2";
// API文檔的版本
public static final String VERSION = "1.0.0";
@Bean
public Docket creatRestApi(){
return new Docket(DocumentationType.SWAGGER_2) // Swagger2類型的文檔
.apiInfo(webApiInfo()) // 設置Api文檔信息
.select() // 返回ApiSelectorBuilder控制哪些接口暴露給Swagger展示
// .paths(Predicates.not(PathSelectors.regex("/error.*"))) // 不監控的路徑
// .paths(PathSelectors.regex("/.*")) // 對根下所有路徑進行監控
.apis(RequestHandlerSelectors.basePackage(SWAGGER2_SCAN_PACKAGE)) // API接口包掃描路徑 - 可省略
.paths(PathSelectors.any()) // 所有路徑都監控
.build(); // 構建Api文檔
}
private ApiInfo webApiInfo(){
return new ApiInfoBuilder()
.title("文檔標題 - xxx的API文檔") // Api文檔的標題
.description("文檔描述 - xxx服務接口定義") // Api文檔的描述
.version(VERSION) // 文檔版本
// 作者、文檔的License信息、聯繫郵箱
.contact(new Contact("LCY","www.liuchengyin.com","[email protected]"))
.build(); // 構建Api文檔信息
}
}
三、創建Pojo、Service、Controller層
1、創建Pojo類
@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value="user對象",description="用戶對象user")
public class User {
private Long id;
@ApiModelProperty(value="用戶名",name="name",example="柳成蔭")
private String name;
@ApiModelProperty(value="性別",name="sex",example="男")
private String sex;
@ApiModelProperty(value="年齡",name="age",example="22")
private Integer age;
}
這個pojo類中前三個註解是lombok
自動生成get\set\constructor的,類上的註解@ApiModel
是對這個pojo類進行說明的。字段上的註解@ApiModelProperty
是對字段進行說明,example屬性即舉例字段。
2、創建Service層
這一層主要就是模擬Service層的操作,沒有其他作用。
@Service
public class UserServiceImpl implements UserService {
@Override
public User getUserById(Long id) {
// 模擬從數據庫中獲取數據
User user = new User();
user.setId(id);
user.setName("lcy");
user.setSex("男");
user.setAge(22);
return user;
}
@Override
public List<User> getAllUser() {
// 模擬從數據庫中獲取數據
List<User> users = new ArrayList<>();
User user1 = new User(1L,"柳成蔭","男",22);
User user2 = new User(2L,"九月清晨","女",18);
users.add(user1);
users.add(user2);
return users;
}
@Override
public User updateUser(User user) {
// 模擬修改數據庫中的數據
return user;
}
@Override
public Integer deleteUserById(Long id) {
// 模擬刪除數據庫中的數據
return 1; // 1表示成功,0表示失敗
}
@Override
public User addUser(User user) {
// 模擬數據庫新增數據
user.setId(3L);
return user;
}
@Override
public Integer uploadFile(MultipartFile file) {
// 模擬上傳文件
return 1; // 1表示成功,0表示失敗
}
}
3、創建Controller層
@RestController
@RequestMapping("/lcy")
@Api(description = "用戶相關接口")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/getUserById/{id}")
@ApiOperation(value = "獲取用戶信息",notes = "根據用戶Id來獲取用戶詳細信息")
@ApiImplicitParam(name = "id",value = "用戶ID",required = true,paramType = "path",dataType = "Long")
public User getUserById(@PathVariable("id") Long id){
return userService.getUserById(id);
}
@GetMapping("/getTest/{id}/{name}")
@ApiOperation(value = "獲取用戶信息",notes = "根據用戶id和name獲取詳細信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id",value = "用戶id",required = true,paramType = "path",dataType = "long"),
@ApiImplicitParam(name = "name",value = "用戶name",required = true,paramType = "path",dataType = "String")
})
public User getUser(@PathVariable Long id,@PathVariable String name){
return new User(id,name,"男",22);
}
@ApiOperation(value = "修改用戶信息",notes = "根據用戶id去修改用戶信息")
@ApiImplicitParam(name = "user",value = "用戶信息",required = true,dataType = "User")
@PutMapping("/updateUser")
public User updateUser(@RequestBody User user){
return userService.updateUser(user);
}
@GetMapping("/getAllUser")
public List<User> getAllUser(){
return userService.getAllUser();
}
@DeleteMapping("/deleteUerById/{id}")
public Integer deleteUserById(@PathVariable Long id){
return userService.deleteUserById(id);
}
@PostMapping("/addUser")
public User addUser(@RequestBody User user){
return userService.addUser(user);
}
@PostMapping("/uploadFile")
public Integer uploadFile(MultipartFile file){
return userService.uploadFile(file);
}
}
該類主要注重@ApiOperation
和@ApiImplicitParam
註解。@ApiOperation
註解主要是對這個接口方法進行說明,@ApiImplicitParam
註解主要是對參數進行說明。
四、啓動項目
啓動SpringBoot
項目,我們通過默認進入swagger頁面的方式進入到文檔頁面localhost:8080/swagger-ui.html
點擊user-controller
展開接口方法。
點開查看詳情,注意因爲是通過路徑獲取參數的(@PathVariable
),因此需要在@ApiImplicitParam
註解裏需要添加屬性paramType = "path"
,否則會出現String無法轉換爲其他類型的錯誤。
在id
輸入框輸入id,點擊下方的try it out
,即可獲取到結果。
上面的截圖是對常用註解和文檔中對應的信息進行解釋,且上面的例子是基本類型的參數,如果參數是對象、上傳的文件,又是怎麼一回事呢?
1、參數爲對象時
當參數是一個User對象,且請求爲PUT請求時。
結果:
當參數是一個User對象,且請求爲POST請求時。
2、參數爲文件時
可以直接選擇文件,是不是很方便。
五、Swagger常見註解
1、標記Pojo的註解
@ApiModel
標記類、@ApiModelProperty
標記屬性字段。
更多信息請見:Swagger註解-@ApiModel 和 @ApiModelProperty、百度
2、標記Controller的註解
①@ApiOperation
用在方法上,說明方法的作用,每一個url資源的定義,使用方式。
②@ApiImplicitParams
、@ApiImplicitParam
對於方法參數的說明,@ApiImplicitParams
裏可以包含多個@ApiImplicitParam
,每一個@ApiImplicitParam
都是一個參數說明。
③@ApiIgnore()
用在方法上,表示忽略該方法,不加入文檔。
④@Api
用在Controller類上,說明該類的作用。可以標記一個Controller類做爲swagger 文檔資源。
更多信息請見:Swagger 常用註解使用詳解、百度