現在我們的項目中已經有了一個可供外部調用的rest api接口,隨着項目的擴展以後會有越來越多的接口,這個時候就需要同時對外部提供關於接口的詳細說明文檔,而swagger幫我們使用很少的時間就可以構建出一套接口文檔。
- 首先在pom.xml中引用swagger所需的依賴。
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
- 然後在代碼中開啓swagger
@Configuration
@EnableSwagger2
/** 是否打開swagger **/
//@ConditionalOnExpression("'${swagger.enable}' == 'true'") 可以動態控制的開關,之後再使用
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// 掃描controller路徑
.apis(RequestHandlerSelectors.basePackage("com.demo.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springt boot 從入門到精通 api")
.description("springt boot 從入門到精通 api")
.termsOfServiceUrl("https://www.jianshu.com/u/c9deb1bda6ce")
.contact("https://www.jianshu.com/u/c9deb1bda6ce")
.version("1.0.0")
.build();
}
}
這一步完成之後,啓動項目,打開 localhost:8080/swagger-ui.html#/就可以看到swagger的界面了,並且我們寫好的那個接口也已經躺在那裏等我們的調用。
swagger還有更多的註解幫助我們完善接口文檔。
從源碼中可以看到swagger提供了這麼多註解,下面我們將常用的幾個進行講解:
@Api
@Api(value = "註解在controller類上", description = "註解在controller類上")
@ApiOperation
@ApiOperation(value = "具體接口描述,寫在controller的方法上, notes = "具體接口描述,寫在controller的方法上")
@ApiModelProperty
@ApiModelProperty(value = "寫在接口對應的實體類的屬性上", example = "值")
@ApiParam
@ApiParam(value = "寫在接口的入參上", required = true)