Swagger
??Swagger號稱是史上最流行的署尤、最好用的API接口文檔構(gòu)建工具甫男,它支持多種語言包括Java在內(nèi)味赃,本文僅關注如何使用Spring Boot來集成Swagger浦辨,更多關于Swagger的介紹可以查看以下幾個鏈接嫂用。
SpringFox
??SpringFox最初叫Swagger-SpringMVC型凳,從字面意義上簡單來理解是使用了SpringMVC來集成Swagger,后來演變成SpringFox這么一個項目(或組織)嘱函,SpringFox官網(wǎng)有這么一句:Automated JSON API documentation for API's built with Spring(針對Spring構(gòu)建的API的自動化JSON API文檔)甘畅。好了,下來我們只需用SpringFox提供的三方庫來快速集成一下Spring Boot和Swagger。
1. 添加Maven依賴
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${latest version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${latest version}</version>
</dependency>
2. 開啟Swagger
??在Spring Boot啟動類上添加@EnableSwagger2即可疏唾。
@SpringBootApplication
@EnableSwagger2 //開啟Swagger
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3. 配置Swagger
??
@Configuration
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// 這里是全局掃描有@Api注解得類蓄氧,還可以掃描任意位置,指定包以及針對方法上的指定注解
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Title")
.description("Description")
.termsOfServiceUrl("")
.contact(new Contact("", "", ""))
.license("")
.licenseUrl("")
.version(" xxx ")
.build();
}
}
4. 運行效果
??啟動Spring Boot后槐脏,可以點擊查看(更改為你的本地地址) http://localhost:8080/swagger-ui.html#/ 喉童,效果如下:
5. 常用注解
??Swagger的所有注解定義在io.swagger.annotations
包下,下面列一些經(jīng)常用到的顿天,未列舉出來的可以另行查閱說明:
Swagger注解 | 簡單說明 |
---|---|
@Api(tags = "xxx模塊說明") | 作用在模塊類上 |
@ApiOperation("xxx接口說明") | 作用在接口方法上 |
@ApiModel("xxxPOJO說明") | 作用在模型類上:如VO堂氯、BO |
@ApiModelProperty(value = "xxx屬性說明",hidden = true) | 作用在類方法和屬性上,hidden設置為true可以隱藏該屬性 |
@ApiParam("xxx參數(shù)說明") | 作用在參數(shù)牌废、方法和字段上咽白,類似@ApiModelProperty |
6. 使用Swagger
??完全以上幾小步配置后,再次打開swagger-ui界面就可以進行測試了鸟缕,相較于傳統(tǒng)的Postman或Curl方式測試接口晶框,使用swagger簡直就是傻瓜式操作,不需要額外說明文檔(寫得好本身就是文檔)而且更不容易出錯懂从,只需要錄入數(shù)據(jù)然后點擊Execute
授段,如果再配合自動化框架,可以說基本就不需要人為操作了莫绣。
End
??Swagger是個優(yōu)秀的工具畴蒲,現(xiàn)在國內(nèi)已經(jīng)有很多的中小型互聯(lián)網(wǎng)公司都在使用它,相較于傳統(tǒng)的要先出Word接口文檔再測試的方式对室,顯然這樣也更符合現(xiàn)在的快速迭代開發(fā)行情模燥。當然了,提醒下大家在正式環(huán)境要記得關閉Swagger掩宜,一來出于安全考慮二來也可以節(jié)省運存蔫骂。之前看到過一篇深入Swagger原理的文章,最后分享出來給大家:API管理工具Swagger介紹及Springfox原理分析牺汤。