說明:本地環境idea + maven3.5 + springboot2.0.0 + springfox-swagger2 2.8.0 + springfox-swagger-ui 2.8.0 + swagger-bootstrap-ui 1.7.2(為了展示的更好看)
1 搭建完Springboot 項目后在pom文件中添加依賴
<springfox-swagger.version>2.8.0</springfox-swagger.version> <swagger-bootstrap-ui.version>1.7.2</swagger-bootstrap-ui.version> <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${springfox-swagger.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${springfox-swagger.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/com.github.xiaoymin/swagger-bootstrap-ui --> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>${swagger-bootstrap-ui.version}</version> </dependency>
2 創建配置類 SwaggerConfig
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket petApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.huitong")) //指定提供接口所在的基包 .build(); } /** * 該套 API 說明,包含作者、簡介、版本、host、服務URL * @return */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("demo api 說明") .contact(new Contact("allen","null","name@example.com")) .version("0.1") .termsOfServiceUrl("localhost:8080/demo1/") .description("demo api") .build(); } }
3 對接口和實體類添加注釋,生成doc。常用的標記如下
@Api()用於類;
標識這個類是swagger的資源
tags–表示分組說明標簽
@ApiOperation()用於方法;
表示一個http請求的操作
value用於方法描述
notes用於提示內容
@ApiModel()用於實體類
表示對類進行說明,用於參數用實體類接收
value–表示對象名
description–描述
@ApiModelProperty()用於實體類字段
表示對model屬性的說明或者數據操作更改
value–字段說明
name–重寫屬性名字
dataType–重寫屬性類型
required–是否必填
example–舉例說明
hidden–隱藏
@ApiImplicitParam() 用於 controller 方法
表示單獨的請求參數
name–參數ming
value–參數說明
dataType–數據類型
paramType–參數類型
example–舉例說明
@ApiImplicitParams() 用於 controller 方法,包含多個 @ApiImplicitParam
@ApiIgnore()用於類或者方法上,可以不被swagger顯示在頁面上
說明:簡單的標記只需要@Api(tags="") 和 @ApiOperation(value="",notes="")
更多關於 注解用法可以參考https://github.com/swagger-api/swagger-core/wiki/Annotations
4 搭建完成后可以測試一波了。啟動服務,在瀏覽器中輸入 http://localhost:8080/swagger-ui.html ,界面如下
在瀏覽器中輸入 http://localhost:8080/doc.html
從中可以看出,swagger 適合作為簡單的 API 文檔,並進行簡單測試。