介紹RESTful API的重磅好伙伴Swagger2,它可以輕松的整合到Spring Boot中,並與Spring MVC程序配合組織出強大RESTful API文檔。
在Spring Boot中使用Swagger2
在pom.xml
中加入Swagger2的依賴:
<!--引入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>
在Application.java
同級創建Swagger2的配置類Swagger2:
package dhccservice.dhccservice; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class Swagger2Configure{ @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .useDefaultResponseMessages(false) .select() .apis(RequestHandlerSelectors.basePackage("dhccservice.dhccservice")) //paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2構建RESTful APIs")//大標題 .description("Spring Boot Swagger2")//詳細描述 .termsOfServiceUrl("http://www.dhcc.com.cn") .contact("seawater")//作者 .version("1.0")//版本 .build(); } }
通過@Configuration
注解,讓Spring來加載該類配置。
再通過@EnableSwagger2
注解來啟用Swagger2。
再通過createRestApi
方法創建Docket
的Bean之后,apiInfo()
用來創建該Api的基本信息(這些基本信息會展現在文檔頁面中)。
select()方法
返回一個ApiSelectorBuilder
實例用來控制哪些接口暴露給Swagger來展現,本例采用指定掃描的包路徑來定義,Swagger會掃描該包下所有Controller定義的API,並產生文檔內容(除了被@ApiIgnore
指定的請求)。
使用@ApiOperation
注解來給API增加說明、通過@ApiImplicitParams
、@ApiImplicitParam
注解來給參數增加說明。
@Api(value = "菜單相關操作",protocols ="http",produces = "100") @RestController public class MenuInfoController { @Autowired private MenuInfoService service; @ApiOperation(value="查詢菜單所有信息",notes = "查詢菜單所有信息",httpMethod = "GET") @ApiImplicitParam(name="menutype",value = "菜單類型",dataType = "String",required = false,paramType = "query") @RequestMapping(value = "/menuInfoAll",method = RequestMethod.GET) public String menuInfoAll(HttpServletRequest request, HttpServletResponse response) { LogWriter.info("dhcc-service","basiccontroller","menuInfoAll"); String arg = request.getQueryString(); arg= PublicUtil.EndecodeStr(arg); String result = service.menuInfoAll(arg); PublicUtil.OutPrint(request, response, result); return null; }
完成上述代碼添加上,啟動Spring Boot程序,訪問:http://localhost:port/swagger-ui.html 就能看到RESTful API的頁面。我們可以再點開具體的API請求,以POST類型的/menuInfoAll請求為例,可找到上述代碼中我們配置的Notes信息以及參數menutype的描述信息。