Swagger2的使用


1.導入swagger依賴

<!--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.加入swagger的配置,可以不用修改,直接使用
@Configuration
@EnableSwagger2
public class Swagger2Config {

@Bean
public Docket webApiConfig(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("webApi")
.apiInfo(webApiInfo())
.select()
.paths(Predicates.not(PathSelectors.regex("/admin/.*")))
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}

private ApiInfo webApiInfo(){
return new ApiInfoBuilder()
.title("網站-課程中心API文檔")
.description("本文檔描述了person接口定義")
.version("1.0")
.contact(new Contact("劉毅", "http://liuyi.com", "312691641@qq.com"))
.build();
}
}

3.Swagger使用的常用注解及其說明:

@Api:用在類上,說明該類的作用。

@ApiOperation:用在方法上,給API增加方法說明。

@ApiParam:用在參數上,給API參數增加說明。

 

例如:

@Api(description = "用戶登陸相關Api")
@Controller
public class PersonController {
  @Autowired
  private PersonServer personServer;
/*
* 刪除方法1占位符格式
* */
@ApiOperation(value = "person刪除數據")
@ResponseBody
@DeleteMapping("/deletePath/{id}")
public Map<String, Object> deletePath( @ApiParam(name="id", value = "講師ID", required = true) @PathVariable("id") Integer id) {
Map<String,Object> result = new HashMap<>();
personServer.deleteById(id);
return result;
}


/*
* 刪除方法2參數格式
* */
@ApiOperation(value = "person刪除數據")
@ResponseBody
@DeleteMapping("/deleteRequest")
public Map<String, Object> deleteRequest( @ApiParam(name="id", value = "講師ID", required = true) @RequestParam("id") Integer id) {
Map<String,Object> result = new HashMap<>();
personServer.deleteById(id);
return result;
}

}

4.啟動Spring Boot主程序,訪問:http://localhost:8080/swagger-ui.html  主要,端口號是自己需要跑起來項目的端口號

例子如下

 

 

 

 

 

 輸入需要刪除的Id,最后點擊 Try it out 就可以愉快的測試啦!

 

 
        
















免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM