詳解spring cloud整合Swagger2構建RESTful服務的APIs,swagger2restful
前言
在前面的部落格中,我們將服務註冊到了Eureka上,可以從Eureka的UI介面中,看到有哪些服務已經註冊到了Eureka Server上,但是,如果我們想查看當前服務提供了哪些RESTful介面方法的話,就無從擷取了,傳統的方法是梳理一篇服務的介面文檔來供開發人員之間來進行交流,這種情況下,很多時候,會造成文檔和代碼的不一致性,比如說代碼改了,但是介面文檔沒有改等問題,而Swagger2則給我們提供了一套完美的解決方案,下面,我們來看看Swagger2是如何來解決問題的。
一、引入Swagger2依賴的jar包
<!-- swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency>
二、初始化Swagger2的配置
@Configuration @EnableSwagger2 // 啟用Swagger2 public class Swagger2 { @Bean public Docket createRestApi() {// 建立API基本資料 return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.chhliu.jpa"))// 掃描該包下的所有需要在Swagger中展示的API,@ApiIgnore註解標註的除外 .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() {// 建立API的基本資料,這些資訊會在Swagger UI中進行顯示 return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2構建RESTful APIs")// API 標題 .description("rdcloud-jpa提供的RESTful APIs")// API描述 .contact("chhliu@")// 連絡人 .version("1.0")// 版本號碼 .build(); } }
註:該配置類需要在Application同級目錄下建立,在項目啟動的時候,就初始化該配置類
三、完善API文檔資訊
public interface SonarControllerI { @ApiOperation(value="擷取項目組Sonar對應的Url資訊", notes="根據id擷取項目組Sonar對應的Url資訊")// 使用該註解描述介面方法資訊 @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "SonarUrl表ID", required = true, dataType = "Long", paramType="path") })// 使用該註解描述方法參數資訊,此處需要注意的是paramType參數,需要配置成path,否則在UI中提供者方法時,會報錯 @GetMapping("/get/{id}") SonarUrl get(@PathVariable Long id); @ApiOperation(value="擷取項目組Sonar對應的所有Url資訊") @GetMapping("/get/all") List<SonarUrl> getAll(); }
註:paramType表示參數的類型,可選的值為"path","body","query","header","form"
四、完善傳回型別資訊
@Entity(name = "SONAR_URL") public class SonarUrl implements Serializable { /** * */ private static final long serialVersionUID = 1L; @ApiModelProperty(value="主鍵", hidden=false, notes="主鍵,隱藏", required=true, dataType="Long")// 使用該註解描述屬性資訊,當hidden=true時,該屬性不會在api中顯示 @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @ApiModelProperty(value="URL連結地址") @Column(name="URL") private String url; @ApiModelProperty(value="項目組") @Column(name="TEAM") private String team; @ApiModelProperty(value="部門") @Column(name="DEPARTMENT") private String department; ……省略getter,setter方法…… }
五、啟動應用
1、在瀏覽器中輸入:http://localhost:7622/swagger-ui.html
2、結果如下:
六、API文檔訪問與測試
Swagger除了提供API介面查看的功能外,還提供了調試測試功能
測試結果如下:
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。