Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化RESTful风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。
1.代码示例
1).在pom.xml文件中引入Swagger2
        <dependency>  
            <groupId>io.springfox</groupId>  
            <artifactId>springfox-swagger2</artifactId>  
            <version>2.6.1</version>
        </dependency>  
        <dependency>  
            <groupId>io.springfox</groupId>  
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>
2).在Application同级目录下添加Swagger2的配置类
package com.example;

import org.springframework.context.annotation.Bean;
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 {
    @Bean
    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("spring boot整合swagger2")
                .termsOfServiceUrl("www.baidu.com")
                .contact("牛头人")
                .version("1.0")
                .build();
    }
}

如上代码所示,通过 @Configuration 注解,让Spring来加载该类配置。再通过 @EnableSwagger2 注解来启用Swagger2。
通过 createRestApi 函数创建 Docket 的Bean之后, apiInfo() 用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。 select() 函数返回一个 ApiSelectorBuilder 实例用来控制哪些接口暴露给Swagger来展现,本例采用指定扫描的包路径来定义,Swagger会扫描该包下所有Controller定义的API,并产生文档内容(除了被 @ApiIgnore 指定的请求)。

3).新建User实体类
package com.example.swagger2;

public class User {
    private String id;
    private String name;
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
}

4).新建SwaggerDemoController类
package com.example.swagger2;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@RestController
@RequestMapping(value="/api")
@Api("SwaggerDemoController相关api")
public class SwaggerDemoController {
    static Map<String, User> users = Collections.synchronizedMap(new HashMap<String, User>());
    
    @ApiOperation(value="获取用户列表", notes="")
    @ApiResponses({
        @ApiResponse(code=400,message="请求参数没填好"),
        @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
    })
    @RequestMapping(value={""}, method=RequestMethod.GET)
    public List<User> getUserList() {
        List<User> r = new ArrayList<User>(users.values());
        return r;
    }
    
    @ApiOperation(value="创建用户", notes="根据User对象创建用户")
    @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    @ApiResponses({
        @ApiResponse(code=400,message="请求参数没填好"),
        @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
    })
    @RequestMapping(value="", method=RequestMethod.POST)
    public String postUser(@RequestBody User user) {
        users.put(user.getId(), user);
        return "success";
    }

@ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID",paramType="path", required = true, dataType = "String")
    @ApiResponses({
        @ApiResponse(code=400,message="请求参数没填好"),
        @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
    })
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public User getUser(@PathVariable String id) {
        System.out.println("id="+id);
        return users.get(id);
    }

@ApiOperation(value="更新用户详细信息", notes="根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID",paramType="path", required = true, dataType = "String"),
            @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    })
    @ApiResponses({
        @ApiResponse(code=400,message="请求参数没填好"),
        @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
    })
    @RequestMapping(value="/{id}", method=RequestMethod.PUT)
    public String putUser(@PathVariable String id, @RequestBody User user) {
        System.out.println("id="+id);
        User u = users.get(id);
        u.setName(user.getName());
        users.put(id, u);
        return "success";
    }

@ApiOperation(value="删除用户", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(name = "id", value = "用户ID",paramType="path", required = true, dataType = "String")
    @ApiResponses({
        @ApiResponse(code=400,message="请求参数没填好"),
        @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
    })
    @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
    public String deleteUser(@PathVariable String id) {
        System.out.println("id="+id);
        users.remove(id);
        return "success";
    }
}
说明:
    @Api:用在类上,说明该类的作用
    @ApiOperation:用在方法上,说明方法的作用
    @ApiImplicitParams:用在方法上包含一组参数说明
    @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
        paramType:参数放在哪个地方
            header-->请求参数的获取:@RequestHeader
            query-->请求参数的获取:@RequestParam
            path(用于restful接口)-->请求参数的获取:@PathVariable
            body(不常用)
            form(不常用)
        name:参数名
        dataType:参数类型
        required:参数是否必须传
        value:参数的意思
        defaultValue:参数的默认值
    @ApiResponses:用于表示一组响应
    @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
        code:数字,例如400
        message:信息,例如"请求参数没填好"
        response:抛出异常的类
    @ApiModel:描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)
        @ApiModelProperty:描述一个model的属性
通过 @ApiOperation 注解来给API增加说明、通过 @ApiImplicitParams 、 @ApiImplicitParam 注解来给参数增加说明。
需要注意的是:

如果ApiImplicitParam中的phone的paramType是query的话,是无法注入到rest路径中的,而且如果是path的话,是不需要配置ApiImplicitParam的,即使配置了,其中的value="用户ID"也不会在swagger-ui展示出来。

具体其他的注解,查看:
https://github.com/swagger-api/swagger-core/wiki/Annotations#apimodel

2.测试:
启动服务,浏览器输入"http://localhost:8080/swagger-ui.html"

GET红框:method=RequestMethod.GET
右边红框:@ApiOperation
parameter红框:@ApiImplicitParams系列注解
response messages红框:@ApiResponses系列注解
输入参数后,点击"try it out!",查看响应内容:

spring boot整合Swagger2的更多相关文章

  1. Spring Boot 项目学习 (四) Spring Boot整合Swagger2自动生成API文档

    0 引言 在做服务端开发的时候,难免会涉及到API 接口文档的编写,可以经历过手写API 文档的过程,就会发现,一个自动生成API文档可以提高多少的效率. 以下列举几个手写API 文档的痛点: 文档需 ...

  2. 2018 最新 spring boot 整合 swagger2 (swagger2 版本 2.8.0)

    好久没上了, 看到又有人回复了. 我就来修改一下. 修改时间  2018年5月16日 这回给你上全新版本. 至发稿时间,所有的包都是新版. 注意: 高版本需要添加  jaxb-api 包, 否则会报错 ...

  3. spring boot 整合 swagger2

    swagger2为了更好的管理api文档接口 swagger构建的api文档如下,清晰,避免了手写api诸多痛点 一,添加依赖 <!--swagger2的官方依赖--> <depen ...

  4. Spring Boot 整合Swagger2构建API文档

    1.pom.xml中引入依赖 <dependency> <groupId>io.springfox</groupId> <artifactId>spri ...

  5. Spring Boot整合JPA、Redis和Swagger2

    好久没有总结了,最近也一直在学习.今天就把spring boot与其它技术的整合做个小总结,主要是jpa.redis和swagger2.公司里有用到这些,整合起来也很简单. 首先,新建一个Spring ...

  6. Spring Boot初识(3)- Spring Boot整合Swagger

    一.本文介绍 如果Web项目是完全前后端分离的话(我认为现在完全前后端分离已经是趋势了)一般前端和后端交互都是通过接口的,对接口入参和出参描述的文档就是Mock文档.随着接口数量的增多和参数的个数增加 ...

  7. Spring Boot之Swagger2集成

    一.Swagger2简单介绍 Swagger2,它可以轻松的整合到Spring Boot中,并与Spring MVC程序配合组织出强大RESTful API文档.它既可以减少我们创建文档的工作量,同时 ...

  8. Spring Boot 整合 Elasticsearch,实现 function score query 权重分查询

    摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 预见未来最好的方式就是亲手创造未来 – <史蒂夫·乔布斯传> 』 运行环境: ...

  9. spring boot整合jsp的那些坑(spring boot 学习笔记之三)

    Spring Boot 整合 Jsp 步骤: 1.新建一个spring boot项目 2.修改pom文件 <dependency>            <groupId>or ...

随机推荐

  1. (KMP 求循环节)The Minimum Length

    http://acm.hust.edu.cn/vjudge/contest/view.action?cid=70325#problem/F The Minimum Length Time Limit: ...

  2. 分离 桂林电子科技大学第三届ACM程序设计竞赛

    链接:https://ac.nowcoder.com/acm/contest/558/H 来源:牛客网 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 262144K,其他语言5242 ...

  3. Delphi事件的广播 转

    http://blog.sina.com.cn/s/blog_44fa172f0102wgs2.html 原文地址:Delphi事件的广播 转作者:MondaySoftware 明天就是五一节了,辛苦 ...

  4. Python学习-26.Python中的三角函数

    Python中的三角函数位于math模块内. 引入模块: import math 输出pi import math print(math.pi) 得:3.141592653589793 math模块内 ...

  5. Hyper-V启动虚拟机,消耗C盘大量磁盘空间

    问题描述 经常使用Hyper-V虚拟机的朋友,可能会碰到这样的现象,当启动某些虚拟机的是否,发现C盘的空间突然减少,减少的空间与虚拟机的内存一样大少. 通过分析C盘空间的磁盘文件,发现在Hyper-V ...

  6. LeetCode142:Linked List Cycle II

    题目: Given a linked list, return the node where the cycle begins. If there is no cycle, return null. ...

  7. 数据导出之winform导出word(三)

    本篇文章补充讲解上篇文章中word模板的制作. ① 新建一个word文档 ② 定位到要插入书签的位置 ③ 菜单栏 “插入” -> “书签”,输入书签名,点击“添加” 可以多处位置使用同样的书签名 ...

  8. 浅谈.NET,C#三层架构(自己总结)

     三层架构 常见架构: 三层(经典) MVC MVVM MVP   开发中常见的23种设计模式: 创建型模式,共五种:工厂方法模式.抽象工厂模式.单例模式.建造者模式.原型模式. 结构型模式,共七种: ...

  9. webform gridview合并单元格

    gridview合并单元格 由于项目要求,需要合并某些单元格,因此特意封装了如下帮助类: /// <summary> /// 合并单元格 /// </summary> publ ...

  10. 从DevOps到Cloud Native,应用上云姿势全解锁

    本文由  网易云发布. 作者:林帆 序文 伴随着IaaS.PaaS等云端基础设施技术的成熟,“应用上云”成为许多企业软件部门的心头大事.通过把传统软件系统搬到云上,一方面可以让业务方获得更多的资源灵活 ...