Json協議串使用
什麼是Swagger2
Swagger2 可以快速幫助我們編寫最新的API介面文件,再也不用擔心開會前仍忙於整理各種資料了,間接提升了團隊開發的溝通效率。常用註解swagger通過註解表明該介面會生成文件,包括介面名、請求方法、引數、返回資訊的等等。
新建工程
首先新建一個SpringBoot工程引入web依賴,再加入今天的主角swagger依賴
<!--整合swagger以及UI--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.6.1</version> </dependency>
建立UserController介面類,以及Swagger2配置類
Swagger類:
@Configuration public class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.java134.demo"))//包的根路徑 .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("springBoot整合swagger")//介面文件標題設定 .description("專案所有API介面列表,www.java134.com")//描述 .version("1.0")//版本號 .build(); }
UserController類:
@Api("UserControllerApi列表")
@RestController
public class UserController {
@ApiOperation(value = "查詢所有資訊",notes = "查詢資料庫中某個學生的資訊")
@GetMapping(value = "/queryAll")
public List<String> queryAll() throws Exception {
List<String> data=new ArrayList<String>();
data.add("java134");
data.add("java資料社群");
return data;
}
@ApiOperation(value="獲取redis中資料", notes="通過key值獲取")
@ApiResponses({
@ApiResponse(code=400,message = "請求報文存在語法錯誤"),
@ApiResponse(code=401,message = "傳送的請求需要有通過 HTTP 認證的認證資訊"),
@ApiResponse(code=403,message = "請求資源的訪問被伺服器拒絕"),
@ApiResponse(code=404,message="伺服器上沒有找到請求的資源")
})
@ApiImplicitParam(name = "key", value = "redis鍵值", required = true, dataType = "String")
@PostMapping(value = "/getRedis")
public String getRedis(String key) throws Exception {
Map<String,String> data=new HashMap<String,String>();
data.put("123","Java資料社群");
data.put("321","Java");
data.put("132","小編");
return data.get(key);
}
@ApiIgnore
@RequestMapping("/index")
public String index() {
return "ApiIgnore=忽略這個介面";
}
}
最後在SpringBoot啟動類中加入@EnbleSwagger2註解,先啟動專案看效果
@SpringBootApplication
@EnableSwagger2
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
訪問:http://localhost:8080/swagger-ui.html 看到如下效果
可以看到Swagger為我們提供了一套很漂亮的視覺化UI,我們UserController類中所有的方法都在這整齊的列出來,不僅如此,我們點開指定的介面還能實現線上測試,測試時對該介面的描述以及引數型別、根據不同狀態碼分別會響應什麼話術描述的很清楚.
回過頭來我們看看UserController加入的一些新註解,下面是Swagger2常用註解分別對應的效果.
@Api:修飾整個類,描述Controller的作用
@ApiOperation:描述一個類的一個方法,或者說一個介面
@ApiParam:單個引數描述
@ApiModel:用物件來接收引數
@ApiProperty:用物件接收引數時,描述物件的一個欄位
@ApiResponse:HTTP響應其中1個描述
@ApiResponses:HTTP響應整體描述
@ApiIgnore:使用該註解忽略這個API
@ApiError :發生錯誤返回的資訊
@ApiImplicitParam:一個請求引數
@ApiImplicitParams:多個請求引數
最後:有什麼不懂的可以加我微信或者我拉你進群同大家一起討論也可以關注我公眾號更多文章等你來看