Swagger是一款RESTFUL接口的文檔在線自動生成+功能測試功能軟件。html
一、pom.xml添加配置web
能夠到http://mvnrepository.com上搜索springfox,即可以看到Springfox Swagger2和Springfox Swagger Ui的版本。spring
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
二、swagger的configurationapi
package com.example.demo; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.swagger.annotations.ApiOperation; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //.apis(RequestHandlerSelectors.basePackage("com.example.demo.web"))//包所在位置 .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .paths(PathSelectors.any()).build().useDefaultResponseMessages(false); } /** * 獲取swagger ApiInfo * * @return */ private static ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API文檔") .description("Swagger API 文檔") .termsOfServiceUrl("http://www.cnblogs.com/gdjlc") .version("1.0") .contact(new Contact("name..", "url..", "email..")) .build(); } }
三、Controller中測試方法app
package com.example.demo.web; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; @RestController @Api(value = "UserController", tags = "用戶操做相關接口") public class UserController { @ResponseBody @GetMapping("/helloWorld") @ApiOperation(value="測試value", notes = "測試notes") @ApiImplicitParam(paramType="query", name = "userName", value = "用戶編號", required = true, dataType = "String") public String helloWorld(@RequestParam String userName){ return "hello world," + userName; } }
Swagger使用的註解及其說明:
@Api:用在類上,說明該類的做用。
@ApiOperation:註解來給API增長方法說明。
@ApiImplicitParams : 用在方法上包含一組參數說明。
@ApiImplicitParam:用來註解來給方法入參增長說明。
@ApiResponses:用於表示一組響應
@ApiResponse:用在@ApiResponses中,通常用於表達一個錯誤的響應信息
@ApiModel:描述一個Model的信息測試
訪問:項目地址/swagger-ui.html,如個人http://localhost:9001/swagger-ui.html
結果以下,能夠點擊方法右邊的【Try it out】按鈕開始測試,以後輸入參數,點擊【Execute】執行查看結果。ui