Swagger2的使用

該技術簡單來說就是給不想寫接口文檔的程序員,這裏包括連postman,eolinker等在線接口文檔都懶的使用的程序猿。
以下關於Swagger2的配置和使用基於Springboot和maven

一、Swagger2介紹

前後端分離開發模式中,api文檔是最好的溝通方式。
Swagger 是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。
1、及時性 (接口變更後,能夠及時準確地通知相關前後端開發人員)
2、規範性 (並且保證接口的規範性,如接口的地址,請求方式,參數及響應格式和錯誤信息)
3、一致性 (接口信息一致,不會出現因開發人員拿到的文檔版本不一致,而出現分歧)
4、可測性 (直接在接口文檔上進行測試,以方便理解業務)

二、配置Swagger2

1、相關依賴

<!--swagger-->
<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>

2、創建Swagger2配置文件


@Configuration
@EnableSwagger2
public class Swagger2Config {

	@Bean
	public Docket adminApiConfig(){

		return new Docket(DocumentationType.SWAGGER_2)
				.groupName("adminApi")
				.apiInfo(adminApiInfo())
				.select()
				// 選出admin前綴的url
				.paths(Predicates.and(PathSelectors.regex("/admin/.*")))
				.build();

	}

	private ApiInfo adminApiInfo(){

		return new ApiInfoBuilder()
				.title("後臺管理系統-課程中心API文檔")
				.description("本文檔描述了後臺管理系統課程中心微服務接口定義")
				.version("1.0")
				.contact(new Contact("Twilight", "https://blog.csdn.net/XlxfyzsFdblj", "[email protected]"))

				.build();
	}
}

3、API模型(實體類)

定義在類上:@ApiModel
定義在屬性上:@ApiModelProperty

@ApiModel(value="Teacher對象", description="講師")
public class Teacher implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "講師ID")
    @TableId(value = "id", type = IdType.ID_WORKER_STR)
    private String id;

    @ApiModelProperty(value = "講師姓名")
    private String name;

    @ApiModelProperty(value = "創建時間", example = "2019-01-01 8:00:00")
    @TableField(fill = FieldFill.INSERT)
    private Date gmtCreate;

    @ApiModelProperty(value = "更新時間", example = "2019-01-01 8:00:00")
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date gmtModified;

}

4、定義接口說明和參數說明

這裏的接口指的是Controller中的暴露給前端的方法。
定義在類上:@Api
定義在方法上:@ApiOperation
定義在參數上:@ApiParam

@Api(description="講師管理")
@RestController
@RequestMapping("/admin/edu/teacher")
public class TeacherAdminController {

	@Autowired
	private TeacherService teacherService;

	@ApiOperation(value = "所有講師列表")
	@GetMapping
	public List<Teacher> list(){
		return teacherService.list(null);
	}

	@ApiOperation(value = "根據ID刪除講師")
	@DeleteMapping("{id}")
	public boolean removeById(
			@ApiParam(name = "id", value = "講師ID", required = true)
			@PathVariable String id){
		return teacherService.removeById(id);
	}
}

5、重啓服務器查看接口

http://localhost:8080/swagger-ui.html
在這裏插入圖片描述
更多使用細則,請參考官方文檔

https://swagger.io/tools/swagger-editor/

發佈了71 篇原創文章 · 獲贊 37 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章