【java框架】SpringBoot(3) -- SpringBoot整合Swagger2
1.SpringBoot web專案整合Swagger2
1.1.認識Swagger2
Swagger 是一個規範和完整的框架,用於生成、描述、呼叫和視覺化 RESTful 風格的 Web 服務。總體目標是使客戶端和介面文件系統作為伺服器以同樣的速度來更新。文件的介面方法,引數和模型緊密整合到伺服器端的程式碼,使用API來保持前後端介面的更新同步。解決了前後端分離開發中的痛點。 Swagger2官方文件:https://swagger.io1.2.整合Swagger2初體驗
①基於SpringBoot Initializr來建立一個web專案,並引入相關依賴:
<!--引入swagger2依賴及ui元件--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
依賴元件下載地址:https://mvnrepository.com/artifact/io.springfox
②建立Swagger2Config配置類,增加API應用配置資訊:
//將此類交給Spring管理,表示一個配置類 @Configuration //開啟Swagger2 @EnableSwagger2 public class Swagger2Config { /** * 建立API應用 * apiInfo() 增加API相關資訊 * 通過select()函式返回一個ApiSelectorBuilder例項,用來控制哪些介面暴露給Swagger來展現, * 本例採用指定掃描的包路徑來定義指定要建立API的目錄 * * @return 返回Swagger的Docket配置Bean例項 */ @Bean public Docket createRestApi(Environment environment) { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .enable(true) //enable是否啟動swagger,如果為False,則swagger不能在瀏覽器中訪問 .select() //指定API物件掃描哪個包下面的controller //引數any():掃描全部; none():都不掃描 //withClassAnnotation:掃描類上的註解,引數是一個註解的反射物件 //withMethodAnnotation:掃描方法上的註解 .apis(RequestHandlerSelectors.basePackage("com.fengye.swagger2.controller")) //過濾什麼路徑 .paths(PathSelectors.any()) .build(); } /** * 建立該API的基本資訊(這些基本資訊會展現在文件頁面中) * 訪問地址:http://專案實際地址/swagger-ui.html * @return 返回API基本資訊 */ private ApiInfo apiInfo() { return new ApiInfoBuilder() //Swagger2展示介面的標題(重要) .title("Spring Boot使用Swagger2構建的Restful API") //描述資訊(主要) .description("Swagger2 makes develop more easily") .version("1.0") .termsOfServiceUrl("https://swagger.io/docs") .license("Apache 2.0") .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0") //作者資訊 .contact(new Contact("fengye", "https://www.cnblogs.com/yif0118/", "[email protected]")).build(); } }
③建立Controller介面類測試介面:
@RestController @RequestMapping("/oss") @Api(value = "介面演示",description = "用來演示Swagger的一些註解") public class TestController { @ApiOperation(value="修改使用者密碼", notes="根據使用者id修改密碼") @ApiImplicitParams({ @ApiImplicitParam(paramType="query", name = "userId", value = "使用者ID", required = true, dataType = "Integer"), @ApiImplicitParam(paramType="query", name = "password", value = "舊密碼", required = true, dataType = "String"), @ApiImplicitParam(paramType="query", name = "newPassword", value = "新密碼", required = true, dataType = "String") }) @RequestMapping("/updatePassword") public String updatePassword(@RequestParam(value="userId") Integer userId, @RequestParam(value="password") String password, @RequestParam(value="newPassword") String newPassword){ if(userId <= 0 || userId > 2){ return "未知的使用者"; } if(StringUtils.isEmpty(password) || StringUtils.isEmpty(newPassword)){ return "密碼不能為空"; } if(password.equals(newPassword)){ return "新舊密碼不能相同"; } return "密碼修改成功!"; } }
④啟動專案,訪問介面url地址資訊:
http://專案實際地址/swagger-ui.html
2.Swagger高階配置應用
2.1.多場景啟用配置
在實際開發場景中,有時我們需要在開發時使用Swagger介面文件,但是在實際上線或生產環境中並不想使用,那麼就需要讀取實際環境資訊進行啟動Swagger。
具體配置如下:
//將此類交給Spring管理,表示一個配置類 @Configuration //開啟Swagger2 @EnableSwagger2 public class Swagger2Config { /** * 建立API應用 * apiInfo() 增加API相關資訊 * 通過select()函式返回一個ApiSelectorBuilder例項,用來控制哪些介面暴露給Swagger來展現, * 本例採用指定掃描的包路徑來定義指定要建立API的目錄 * * @return 返回Swagger的Docket配置Bean例項 */ @Bean public Docket createRestApi(Environment environment) { //設定要顯示的Swagger環境 Profiles profiles = Profiles.of("dev", "test"); //獲取當前專案中的環境,看是否一致 boolean flag = environment.acceptsProfiles(profiles); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .enable(flag) //enable是否啟動swagger,如果為False,則swagger不能在瀏覽器中訪問 .select() //指定API物件掃描哪個包下面的controller //引數any():掃描全部; none():都不掃描 //withClassAnnotation:掃描類上的註解,引數是一個註解的反射物件 //withMethodAnnotation:掃描方法上的註解 .apis(RequestHandlerSelectors.basePackage("com.fengye.swagger2.controller")) //過濾什麼路徑 .paths(PathSelectors.any()) .build(); } }
同時設定相關的環境配置資訊:
application.properties:
#確認啟用開發環境--swagger啟用 spring.profiles.active=dev
application-dev.properties與application-pro.properties:
server.port=8081 #開發環境 server.port=8082 #生產環境
2.2.介面文件分組顯示
在實際專案開發過程中,一個專案開發者有成百上千個介面文件,如果不進行分組,那麼集合在一個Swagger頁面中的介面就會很多,不便於查詢和展示,
那麼對不同的開發者來進行分組顯示,不同的開發者命名自己的開發介面,就非常有必要了。
而Swagger配置中提供了groupName()進行分組顯示:
@Bean public Docket devDocket1(){ //由開發者自己管理對應的類,編寫controller對應的包 return new Docket(DocumentationType.SWAGGER_2).groupName("A"); } @Bean public Docket devDocket2(){ return new Docket(DocumentationType.SWAGGER_2).groupName("B"); } @Bean public Docket devDocket3(){ return new Docket(DocumentationType.SWAGGER_2).groupName("C"); }
分組效果:
2.3.Swagger Api介面註釋
常用到的註解有:
- Api
- ApiModel
- ApiModelProperty
- ApiOperation
- ApiParam
- ApiResponse
- ApiResponses
- ResponseHeader
①Api
Api 用在類上,說明該類的作用。可以標記一個Controller類做為swagger 文件資源,使用方式:
@Api(value = "/user", description = "Operations about user")
②ApiOeration
ApiOperation:用在方法上,說明方法的作用,每一個url資源的定義,使用方式:
@ApiOperation( value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order, tags = {"Pet Store"})
③ApiParam
ApiParam請求屬性,使用方式:
public ResponseEntity<User> createUser(@RequestBody @ApiParam(value = "Created user object", required = true) User user)
與Controller中的方法並列使用。
④ApiResponse
ApiResponse:響應配置,使用方式:
@ApiResponse(code = 400, message = "Invalid user supplied")
⑤ApiResponses
ApiResponses:響應集配置,使用方式:
@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
⑥ResponseHeader
響應頭設定,使用方法:
@ResponseHeader(name="head1",description="response head conf")
⑦其它
- @ApiImplicitParams:用在方法上包含一組引數說明;
- @ApiImplicitParam:用在@ApiImplicitParams註解中,指定一個請求引數的各個方面
- paramType:引數放在哪個地方
- name:引數代表的含義
- value:引數名稱
- dataType: 引數型別,有String/int,無用
- required : 是否必要
- defaultValue:引數的預設值
- @ApiResponses:用於表示一組響應;
- @ApiResponse:用在@ApiResponses中,一般用於表達一個錯誤的響應資訊;
- code: 響應碼(int型),可自定義
- message:狀態碼對應的響應資訊
- @ApiModel:描述一個Model的資訊(這種一般用在post建立的時候,使用@RequestBody這樣的場景,請求引數無法使用@ApiImplicitParam註解進行描述的時候;
- @ApiModelProperty:描述一個model的屬性。
本部落格寫作參考文件相關:
https://www.jianshu.com/p/66a14ea07622 《簡書--Swagger使用手冊》
https://www.jianshu.com/p/12f4394462d5 《簡書--Swagger常用註解說明》
https://swagger.io/irc/
示例程式碼已上傳至Github地址:
https://github.com/devyf/SpringBoot_Study/tree/master/springboot_swagger2