前言
在前面的博客中,我們將服務注冊到了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接口查看的功能外,還提供了調試測試功能
測試結果如下:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答
圖片精選