当前位置: 首页 > news >正文

springboot集成swagger

一、加入依赖

<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>

二、创建Swagger2配置类

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();
    }
}

三、代码示例

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);
    }
}

四、生成的文档效果(http://127.0.0.1:8080/oaframe/swagger-ui.html)

 

五、各个注解的介绍(转载自https://www.cnblogs.com/hyl8218/p/8520994.html)

常用到的注解有:
  • Api
  • ApiModel
  • ApiModelProperty
  • ApiOperation
  • ApiParam
  • ApiResponse
  • ApiResponses
  • ResponseHeader
1. api标记

Api 用在类上,说明该类的作用。可以标记一个Controller类做为swagger 文档资源,使用方式:

@Api(value = "/user", description = "Operations about user") 

与Controller注解并列使用。 属性配置:

属性名称备注
valueurl的路径值
tags如果设置这个值、value的值会被覆盖
description对api资源的描述
basePath基本路径可以不配置
position如果配置多个Api 想改变显示的顺序位置
producesFor example, "application/json, application/xml"
consumesFor example, "application/json, application/xml"
protocolsPossible values: http, https, ws, wss.
authorizations高级特性认证时配置
hidden配置为true 将在文档中隐藏

在SpringMvc中的配置如下:

@Controller
@RequestMapping(value = "/api/pet", produces = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE})
@Api(value = "/pet", description = "Operations about pets") public class PetController { } 
2. ApiOperation标记

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中的方法并列使用。
属性配置:

属性名称备注
valueurl的路径值
tags如果设置这个值、value的值会被覆盖
description对api资源的描述
basePath基本路径可以不配置
position如果配置多个Api 想改变显示的顺序位置
producesFor example, "application/json, application/xml"
consumesFor example, "application/json, application/xml"
protocolsPossible values: http, https, ws, wss.
authorizations高级特性认证时配置
hidden配置为true 将在文档中隐藏
response返回的对象
responseContainer这些对象是有效的 "List", "Set" or "Map".,其他无效
httpMethod"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH"
codehttp的状态码 默认 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"); } } 
3. ApiParam标记

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) 
4. ApiResponse

ApiResponse:响应配置,使用方式:

@ApiResponse(code = 400, message = "Invalid user supplied") 

与Controller中的方法并列使用。 属性配置:

属性名称备注
codehttp的状态码
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(""); } 
5. ApiResponses

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(""); } 
6. ResponseHeader

响应头设置,使用方法

@ResponseHeader(name="head1",description="response head conf")

与Controller中的方法并列使用。 属性配置:

属性名称备注
name响应头名称
description头描述
response默认响应类 Void
responseContainer参考ApiOperation中配置

在SpringMvc中的配置如下:

@ApiModel(description = "群组")
7. 其他
  • @ApiImplicitParams:用在方法上包含一组参数说明;
  • @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
    • paramType:参数放在哪个地方
    • name:参数代表的含义
    • value:参数名称
    • dataType: 参数类型,有String/int,无用
    • required : 是否必要
    • defaultValue:参数的默认值
  • @ApiResponses:用于表示一组响应;
  • @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息;
    • code: 响应码(int型),可自定义
    • message:状态码对应的响应信息
  • @ApiModel:描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候;
  • @ApiModelProperty:描述一个model的属性。

 

转载于:https://www.cnblogs.com/Garnett-Boy/p/10143125.html

相关文章:

  • kentico中的page template的使用
  • 解决奇葩的win7文件不能拖动问题
  • layer
  • RSA加密算法的简单案例
  • 第二次作业
  • Oracle数据库入门——初级系列教程
  • CentOS 网络基础:(4)设置单网卡多IP
  • PostgreSQL 9.6 for Centos7.4 最佳实践安装
  • charles抓包工具
  • OpenSL ES
  • C#.NET 剪切板复制粘贴泛型的例子代码参考 Clipboard Copy Paste List
  • 关于《停止学习框架》 - 讨论
  • Educational Codeforces Round 33 (Rated for Div. 2) E. Counting Arrays [数论II][组合数学]
  • [学习笔记]拉格朗日插值
  • 网络的分类
  • php的引用
  • 时间复杂度分析经典问题——最大子序列和
  • 10个确保微服务与容器安全的最佳实践
  • 2017-08-04 前端日报
  • CAP 一致性协议及应用解析
  • classpath对获取配置文件的影响
  • ComponentOne 2017 V2版本正式发布
  • co模块的前端实现
  • ES6之路之模块详解
  • java8 Stream Pipelines 浅析
  • React-flux杂记
  • 订阅Forge Viewer所有的事件
  • 基于Vue2全家桶的移动端AppDEMO实现
  • 漫谈开发设计中的一些“原则”及“设计哲学”
  • 前端技术周刊 2019-01-14:客户端存储
  • 微信小程序上拉加载:onReachBottom详解+设置触发距离
  • 小程序上传图片到七牛云(支持多张上传,预览,删除)
  • 曾刷新两项世界纪录,腾讯优图人脸检测算法 DSFD 正式开源 ...
  • ​LeetCode解法汇总2583. 二叉树中的第 K 大层和
  • ​secrets --- 生成管理密码的安全随机数​
  • #pragma data_seg 共享数据区(转)
  • #QT(串口助手-界面)
  • #我与Java虚拟机的故事#连载18:JAVA成长之路
  • %@ page import=%的用法
  • (33)STM32——485实验笔记
  • (C语言)二分查找 超详细
  • (ZT)出版业改革:该死的死,该生的生
  • (附源码)springboot家庭财务分析系统 毕业设计641323
  • (附源码)springboot码头作业管理系统 毕业设计 341654
  • (附源码)ssm高校升本考试管理系统 毕业设计 201631
  • (九)One-Wire总线-DS18B20
  • (五)Python 垃圾回收机制
  • (一)插入排序
  • (转)jQuery 基础
  • (转)Linux NTP配置详解 (Network Time Protocol)
  • (转载)微软数据挖掘算法:Microsoft 时序算法(5)
  • .NET Micro Framework 4.2 beta 源码探析
  • .NET/C# 编译期间能确定的相同字符串,在运行期间是相同的实例
  • .NET企业级应用架构设计系列之技术选型
  • .NET上SQLite的连接