一、pom文件下加入以下依賴
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.8.0</version> </dependency>
版本信息,可以通過swagger官網查詢,或通過maven倉庫搜索!
二、在項目中加入配置類
import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; 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 Swagger2Config { public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select()
.apis(RequestHandlerSelectors.basePackage("com.example")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("Spring Boot————Swagger2構建Restful APIs") .description("消息中心使用") .termsOfServiceUrl("https://swagger.io") .version("1.0") .build(); } }
三、在對應的controller中使用Restful Api的相關注解,如下:
//代替@responsebody和@Controller,返回json格式 @RestController //方法的描述 @ApiOperation //單個參數 @ApiImplicitParam(name = "",value = "",requires = true/false,dataType = "") //多個參數 @ApiImplicitParams{ @ApiImplicitParam(name = "",value = "",requires = true/false,dataType = ""), @ApiImplicitParam(name = "",value = "",requires = true/false,dataType = "") } //配置url映射 @RequestMapping //url中占位參數 @PathVariable
開啟本地服務,訪問http://localhost:8080/swagger-ui.html,即可看到相應界面!
附:RESTFUL API各請求方法如下,
1.GET
一般用於執行查詢操作。get請求中URL有長度限制,並且url中的數據都明文暴露。
2.POST
在做一些修改的操作的時候使用,突破了長度限制,且數據存放在body中。
3.HEAD
HEAD請求只會返回首部的信息,不會返回相應體。通常用於測試數據是否存在,可以做心跳測試等。
4.PUT
與GET相反,用於改變某些內容。
5.DELETE
刪除某些資源時使用。
6.TRACE
用於觀察某一請求在到達服務前的變化,該請求會在到達服務前的最后一步返回原始信息,以此來觀察到,數據在中間傳輸時是否有過修改。
經常用於跨站攻擊,有一定的安全隱患。
7.OPTIONS
詢問服務器支持的方法
8.PATCH
用於更新部分字段時使用,區別於PUT的全部提交,當更新的部分數據不存在時則新建,類似於neworupdate。
更多詳情可查看RESTFUL架構詳解