環境搭建
- 創建maven工程
- 編輯pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>
</dependencies>
- 編輯Swagger2Config配置
@Configuration
@EnableSwagger2
public class Swagger2Config {
//swagger2的配置文件,這裏可以配置swagger2的一些基本的內容,比如掃描的包等等
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//爲當前包路徑
.apis(RequestHandlerSelectors.basePackage("com.lc.controller"))
.paths(PathSelectors.any())
.build();
}
//構建 api文檔的詳細信息函數,注意這裏的註解引用的是哪個
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//頁面標題
.title("Spring Boot 測試使用 Swagger2 構建RESTful API")
//創建人
.contact(new Contact("lc", "http://www.baidu.com", ""))
//版本號
.version("1.0")
//描述
.description("API 描述")
.build();
}
}
- 編寫Controller類
@RestController
@Api("swaggerTestController相關api") //作用於類上,表示這個類是swagger的資源。
public class TestController {
@ApiOperation(value = "根據id查詢信息", notes = "查詢數據庫中某人的信息")//用在請求的方法上,說明的方法的作用和用法
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用戶id", dataType = "String", paramType = "query", example = "1112") })//用在請求的方法上,表示一組參數說明,可以包含多個@ApiImplicitParam()
@ApiResponses({ @ApiResponse(code = 400, message = "請求參數沒有填好"), @ApiResponse(code = 404, message = "請求路徑沒有找到") })//用在請求的方法上,表示一組響應。可以包含多個@ApiResponse()
@GetMapping(value = "testRest/{id}")
public RestMessage testGetResetful(@PathVariable String id) {
RestMessage restMessgae = new RestMessage();
System.out.println(id);
return restMessgae;
}
}
- 編寫返回響應數據類
@ApiModel(description = "返回響應數據")//用在響應類上,表示一個返回響應數據的信息
public class RestMessage {
@ApiModelProperty(value = "錯誤信息")//用在屬性上,描述響應類的屬性
private String message;
@ApiModelProperty(value = "狀態碼")
private String code;
@ApiModelProperty(value = "返回的數據")
private Object data;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
- 編寫啓動類
- 在瀏覽器中輸入 http:localhost:8080/swagger-ui.html
- 在swagger頁面填寫接口參數即可進行測試