1、加入依赖css
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
2、建立Swagger2配置类html
package com.sxdx.oa_service.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.RestController; 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 SwaggerConfiguration { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //.apis(RequestHandlerSelectors.basePackage("com.sxdx.oa_service"))//配置须要生成文档的扫码路径 .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))//配置须要生成文档的类型,此处为全部添加了@RestController注解的类 .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("RESTful APIs") .description("oa_frame 接口文档") //.termsOfServiceUrl("http://easonjim.com/") .contact("高一鹏") .version("1.0") .build(); } }
3、代码示例java
package com.sxdx.oa_service.springCacheTest.controller; import com.sxdx.oa_service.bootTest.bean.JsonResult; import com.sxdx.oa_service.springCacheTest.model.Department; import com.sxdx.oa_service.springCacheTest.service.CacheTestService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @Api(value = "缓存练习接口",tags = {"缓存练习接口"},description="用于练习spring缓存及redis",hidden = false) public class CacheTestController { @Autowired private CacheTestService cacheTestService; @ApiOperation( value = "经过id查询部门信息", notes="经过id查询部门信息") @GetMapping(value = "selectDeptById/{id}") public ResponseEntity<JsonResult> selectByPrimaryKey(@PathVariable Integer id){ JsonResult r = new JsonResult(); try { Department department = cacheTestService.selectByPrimaryKey(id); r.setResult(department); r.setStatus("success"); } catch (Exception e) { r.setResult(e.getClass().getName() + ":" + e.getMessage()); r.setStatus("failure"); e.printStackTrace(); } return ResponseEntity.ok(r); } @ApiOperation(value = "修改部门信息", notes="修改部门信息") @PostMapping(value = "updateByPrimaryKeySelective") public ResponseEntity<JsonResult> updateByPrimaryKeySelective(@RequestBody Department dept){ JsonResult r = new JsonResult(); try { Department department = cacheTestService.updateByPrimaryKeySelective(dept); r.setResult(department); r.setStatus("success"); } catch (Exception e) { r.setResult(e.getClass().getName() + ":" + e.getMessage()); r.setStatus("failure"); e.printStackTrace(); } return ResponseEntity.ok(r); } @ApiOperation(value = "经过id 删除部门", notes="经过id 删除部门") @GetMapping (value = "deleteDeptById/{id}") public ResponseEntity<JsonResult> updateByPrimaryKeySelective(@PathVariable Integer id){ JsonResult r = new JsonResult(); try { int num = cacheTestService.deleteByPrimaryKey(id); r.setResult("已删除"); r.setStatus("success"); } catch (Exception e) { r.setResult(e.getClass().getName() + ":" + e.getMessage()); r.setStatus("failure"); e.printStackTrace(); } return ResponseEntity.ok(r); } }
4、生成的文档效果(http://127.0.0.1:8080/oaframe/swagger-ui.html)web
5、各个注解的介绍(转载自https://www.cnblogs.com/hyl8218/p/8520994.html)redis
Api 用在类上,说明该类的做用。能够标记一个Controller类作为swagger 文档资源,使用方式:spring
@Api(value = "/user", description = "Operations about user")
与Controller注解并列使用。 属性配置:json
属性名称 | 备注 |
---|---|
value | url的路径值 |
tags | 若是设置这个值、value的值会被覆盖 |
description | 对api资源的描述 |
basePath | 基本路径能够不配置 |
position | 若是配置多个Api 想改变显示的顺序位置 |
produces | For example, "application/json, application/xml" |
consumes | For example, "application/json, application/xml" |
protocols | Possible values: http, https, ws, wss. |
authorizations | 高级特性认证时配置 |
hidden | 配置为true 将在文档中隐藏 |
在SpringMvc中的配置以下:api
@Controller @RequestMapping(value = "/api/pet", produces = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE}) @Api(value = "/pet", description = "Operations about pets") public class PetController { }
ApiOperation:用在方法上,说明方法的做用,每个url资源的定义,使用方式:缓存
@ApiOperation( value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order, tags = {"Pet Store"})
与Controller中的方法并列使用。
属性配置:ruby
属性名称 | 备注 |
---|---|
value | url的路径值 |
tags | 若是设置这个值、value的值会被覆盖 |
description | 对api资源的描述 |
basePath | 基本路径能够不配置 |
position | 若是配置多个Api 想改变显示的顺序位置 |
produces | For example, "application/json, application/xml" |
consumes | For example, "application/json, application/xml" |
protocols | Possible values: http, https, ws, wss. |
authorizations | 高级特性认证时配置 |
hidden | 配置为true 将在文档中隐藏 |
response | 返回的对象 |
responseContainer | 这些对象是有效的 "List", "Set" or "Map".,其余无效 |
httpMethod | "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH" |
code | http的状态码 默认 200 |
extensions | 扩展属性 |
在SpringMvc中的配置以下:
@RequestMapping(value = "/order/{orderId}", method = GET) @ApiOperation( value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags = { "Pet Store" }) public ResponseEntity<Order> getOrderById(@PathVariable("orderId") String orderId) throws NotFoundException { Order order = storeData.get(Long.valueOf(orderId)); if (null != order) { return ok(order); } else { throw new NotFoundException(404, "Order not found"); } }
ApiParam请求属性,使用方式:
public ResponseEntity<User> createUser(@RequestBody @ApiParam(value = "Created user object", required = true) User user)
与Controller中的方法并列使用。
属性配置:
属性名称 | 备注 |
---|---|
name | 属性名称 |
value | 属性值 |
defaultValue | 默认属性值 |
allowableValues | 能够不配置 |
required | 是否属性必填 |
access | 不过多描述 |
allowMultiple | 默认为false |
hidden | 隐藏该属性 |
example | 举例子 |
在SpringMvc中的配置以下:
public ResponseEntity<Order> getOrderById(
@ApiParam(value = "ID of pet that needs to be fetched", allowableValues = "range[1,5]", required = true) @PathVariable("orderId") String orderId)
ApiResponse:响应配置,使用方式:
@ApiResponse(code = 400, message = "Invalid user supplied")
与Controller中的方法并列使用。 属性配置:
属性名称 | 备注 |
---|---|
code | http的状态码 |
message | 描述 |
response | 默认响应类 Void |
reference | 参考ApiOperation中配置 |
responseHeaders | 参考 ResponseHeader 属性配置说明 |
responseContainer | 参考ApiOperation中配置 |
在SpringMvc中的配置以下:
@RequestMapping(value = "/order", method = POST) @ApiOperation(value = "Place an order for a pet", response = Order.class) @ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") }) public ResponseEntity<String> placeOrder( @ApiParam(value = "order placed for purchasing the pet", required = true) Order order) { storeData.add(order); return ok(""); }
ApiResponses:响应集配置,使用方式:
@ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })
与Controller中的方法并列使用。 属性配置:
属性名称 | 备注 |
---|---|
value | 多个ApiResponse配置 |
在SpringMvc中的配置以下:
@RequestMapping(value = "/order", method = POST) @ApiOperation(value = "Place an order for a pet", response = Order.class) @ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") }) public ResponseEntity<String> placeOrder( @ApiParam(value = "order placed for purchasing the pet", required = true) Order order) { storeData.add(order); return ok(""); }
响应头设置,使用方法
@ResponseHeader(name="head1",description="response head conf")
与Controller中的方法并列使用。 属性配置:
属性名称 | 备注 |
---|---|
name | 响应头名称 |
description | 头描述 |
response | 默认响应类 Void |
responseContainer | 参考ApiOperation中配置 |
在SpringMvc中的配置以下:
@ApiModel(description = "群组")