Note
  • Introduction
  • JS
    • JS / JQuery 代码、框架收藏
    • 用Mock.js + AngularJS来提高开发效率
    • 在JavaScript中监听 IME 键盘输入事件
    • 如何组织大型JavaScript应用中的代码?
    • 深入理解javascript原型和闭包
      • 1. 一切都是对象
      • 2. 函数和对象的关系
      • 3. prototype原型
      • 4. 隐式原型
      • 5. instanceof
      • 6. 继承
      • 7. 原型的灵活性
      • 8. 简述【执行上下文】上
      • 9. 简述【执行上下文】下
      • 10. this
      • 11. 执行上下文栈
      • 12. 简介【作用域】
      • 13. 【作用域】和【上下文环境】
      • 14. 从【自由变量】到【作用域链】
      • 15. 闭包
      • 16. 补充:上下文环境和作用域的关系
    • AngularJS
      • AngularJS开发一些经验总结
      • AngularJS Controller 间通信机制
      • AngularJS 中的一些坑
      • 如何解决AngularJs在IE下取数据总是缓存的问题
      • AngularJS之$timeout指令
      • angular 代码日记
      • AngularJS Directive 隔离 Scope 数据交互
      • 在Angular指令中使用NgModelController做数据绑定
      • AngularJS的ngTransclude
      • 使用Angularjs的ng-cloak指令避免页面乱码
      • Directive - Compile vs. Link
    • NodeJS
      • npm的配置管理及设置代理
    • Angular
      • Angular2 - Control Validation on blur
      • Angular2 - how to call component function from outside the app
  • Go
    • How to Test Local Changes with Go Mod
  • Java
    • Java中根据字体得到字符串高度和长度
    • JAVA 判断一个字符串是不是一个合法的日期格式
    • JVM上的随机数与熵池策略
    • tomcat7+jdk的keytool生成证书 配置https
    • Spring
      • SpringMVC中用@ParamVariable传递的参数包含斜杠(/)时,匹配不了报404错误的解决方案
      • SpringMVC 中HttpMessageConverter简介和Http请求415 Unsupported Media Type的问题
      • Spring Boot 打包,分离依赖jar,配置文件
      • SpringBoot启动后 Stopping service [Tomcat]
      • spring-boot打包时排除第三方依赖
    • 第一个Eclipse插件
    • Eclipse 使用技巧
    • HighChart利用servlet导出中文PNG图片乱码问题解决
    • JDK中文字体在Linux操作系统的设置方案
    • Shiro
      • Shiro-Authentication(身份验证)
      • Shiro-Authorization(授权)
    • 详谈再论JAVA获取本机IP地址
  • Python
    • pip国内镜像源的配置
  • Linux
    • Shell脚本 bad interpreter:No such file or directory & /bin/bash^M: bad interpreter错误解决方法
    • 10个重要的Linux ps命令实战
    • Linux 下执行定时任务 crontab 命令详解
    • CentOS 7.x设置自定义开机启动,添加自定义系统服务
    • CentOS 7 下使用 Firewall
    • 在Ubuntu 12.04安装和设置SSH服务
    • 配置CENTOS YUM更新源
    • Linux下终端利器tmux
    • scp命令
    • Linux系统管理常用命令
    • 让你提升命令行效率的 Bash 快捷键 [完整版]
    • SELinux
    • Linux下 RabbitMQ的安装与配置
    • SELinux下更改mysql端口
    • centos 7 升级后yum install出现Exiting on user cancel
    • Linux Shell 通配符、元字符、转义符使用实例介绍
  • Other
    • Docker
      • Docker Proxy
    • Swagger
      • Spring MVC 集成 Swagger
    • Maven
      • maven plugin的execution出错
      • nexus repair或update index 没反应 速度慢 手动配置nexus index
      • nexus 搭建 maven 私服
      • Maven类包冲突终极解决小技若干
      • org.codehaus.plexus.archiver.jar.Manifest.merge(org.codehaus.plexus.archiver.jar.Manifest)
      • Maven 生命周期
      • wagon-maven-plugin
      • Maven中-DskipTests和-Dmaven.test.skip=true的区别
    • MySQL
      • is not allowed to connect to this MySQL server 解决办法
      • MySQL备份--mysql dump
      • MySQL启动中 InnoDB: Error: log file ./ib_logfile0 is of different size 0 5242880 bytes 的问题
      • MySQL修改root密码的多种方法
      • MySQL长事务导致的Table Metadata Lock
      • com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
      • 解决mysql插入数据时出现Incorrect string value: '\xF0\x9F...' for column 'name' at row 1的异常
    • HTTP
      • HTTP 协议中的 Transfer-Encoding
      • 四种常见的 POST 提交数据方式
      • HTTP 请求头中的 X-Forwarded-For
      • 传统轮询、长轮询、服务器发送事件与WebSocket
    • Raspberry
      • 系统安装配置
    • VIM
      • vim常用配置
      • 在vim中使用查找命令查找指定字符串
      • Vim缩进有关的设置总结
    • Git
      • github 同步一个 fork
      • Git 如何 clone 非 master 分支的代码
      • git提示error setting certificate verify locations解决办法
      • git设置和取消代理
      • How to Delete Commit History in Github
      • Windows下使用Beyond Compare作为git的比对与合并工具
    • 解决 Virtualbox 共享文件夹 cannot create symlink error 问题
    • nginx 403 forbidden 二种原因
    • VirtualBox的四种网络连接方式
    • 在Windows的CMD中如何设置支持UTF8编码?
    • nginx使用ssl模块配置HTTPS支持
    • 怎么查看WINDOWS端口被哪个程序占用
    • VMWare 随系统启动指定虚拟机
    • 使用命令行启动VirtualBox虚拟机
    • 该死的^M
    • install home-assistant mosquitto-broker and node-red on android
    • SSH原理与运用:远程登录、远程操作与端口转发
    • SVN mime-type 笔记
    • VirtualBox虚拟机网络配置(NAT + Host-only - Bridged)
    • VirtualBox绿色版的桥接网卡驱动安装
    • OAuth的改变
    • MavenActionUtil.getMavenProject(e.getDataContext()) is Null when developing a intellij plugin
    • Cygwin的安装和配置apt-cyg源
    • Zookeeper运维常用四字命令
    • svn sqlite[S11]: database disk image is malformed
Powered by GitBook
On this page
  • 引入特定的依赖 JAR 包
  • 添加Swagger配置
  • 将配置注入到容器
  • 集成 Swagger-ui界面
  • 使用Swagger特定注解

Was this helpful?

  1. Other
  2. Swagger

Spring MVC 集成 Swagger

Swagger 是一个API文档生成工具,它支持各种语言,甚至支持在线运行实例。

引入特定的依赖 JAR 包

pom.xml 中添加如下依赖:

<dependency>
    <groupId>com.mangofactory</groupId>
    <artifactId>swagger-springmvc</artifactId>
    <version>1.0.2</version>
</dependency>
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>15.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.4.4</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.4</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.4.4</version>
</dependency>

添加Swagger配置

这里使用 JavaConfig 的方法配置Swagger, 配置类为 SwaggerConfig

package yay.apidoc.config;

import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
import com.mangofactory.swagger.models.dto.ApiInfo;
import com.mangofactory.swagger.plugin.EnableSwagger;
import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

/**
 * @author albert
 * @version 1.0
 * @since JDK 1.7
 */
@Configuration
@EnableSwagger
@EnableWebMvc
public class SwaggerConfig {

    private SpringSwaggerConfig springSwaggerConfig;

    /**
     * Required to autowire SpringSwaggerConfig
     */
    @Autowired
    public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig)
    {
        this.springSwaggerConfig = springSwaggerConfig;
    }

    /**
     * Every SwaggerSpringMvcPlugin bean is picked up by the swagger-mvc
     * framework - allowing for multiple swagger groups i.e. same code base
     * multiple swagger resource listings.
     */
    @Bean
    public SwaggerSpringMvcPlugin customImplementation()
    {
        return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
                .apiInfo(apiInfo())
                .includePatterns(".*");
    }

    private ApiInfo apiInfo()
    {
        ApiInfo apiInfo = new ApiInfo(
                "Spring MVC Demo",
                "Spring MVC 简单示例,依赖于 MySQL 数据库,只有简单的登陆功能。",
                "开发者: Albert Chen",
                "albert.chen.dao@gmail.com",
                "MIT License",
                "/LICENSE");
        return apiInfo;
    }
}

新增一个Controller

package yay.apidoc.controller;

import io.swagger.annotations.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import yay.apidoc.model.UamGroup;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by yuananyun on 2015/11/23.
 */
@Controller
@RequestMapping(value = "/group", produces = {"application/json;charset=UTF-8"})
@Api(value = "/group", description = "群组的相关操作")
public class GroupController {
    @RequestMapping(value = "addGroup", method = RequestMethod.PUT)
    @ApiOperation(notes = "addGroup", httpMethod = "POST", value = "添加一个新的群组")
    @ApiResponses(value = {@ApiResponse(code = 405, message = "invalid input")})
    public UamGroup addGroup(@ApiParam(required = true, value = "group data") @RequestBody UamGroup group) {
        return group;
    }

    @RequestMapping(value = "getAccessibleGroups", method = RequestMethod.GET)
    @ApiOperation(notes = "getAccessibleGroups", httpMethod = "GET", value = "获取我可以访问的群组的列表")
    public List<UamGroup> getAccessibleGroups() {
        UamGroup group1 = new UamGroup();
        group1.setGroupId("1");
        group1.setName("testGroup1");

        UamGroup group2 = new UamGroup();
        group2.setGroupId("2");
        group2.setName("testGroup2");

        List<UamGroup> groupList = new LinkedList<UamGroup>();
        groupList.add(group1);
        groupList.add(group2);

        return groupList;
    }
}

其中UamGroup的定义如下:

package yay.apidoc.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

/**
 * 群组
 */
@ApiModel
public class UamGroup {
    /**
     * 编号
     */
    @ApiModelProperty(value = "群组的Id", required = true)
    private String groupId;
    /**
     * 名称
     */
    @ApiModelProperty(value = "群组的名称", required = true)
    private String name;
    /**
     * 群组图标
     */
    @ApiModelProperty(value = "群组的头像", required = false)
    private String icon;

    public String getGroupId() {
        return groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }
}

将配置注入到容器

在 DispatcherServlet 的配置 ~servlet.xml 里注入 Swagger 配置对象:

    <context:component-scan base-package="yay.apidoc.controller"/>

集成 Swagger-ui界面

然后在 user-servlet.xml 里添加这些静态文件映射:

    <mvc:resources mapping="/swagger/**" location="/WEB-INF/swagger-ui/"/>

使用Swagger特定注解

Swagger 包含了一些特定的注解,可以更好的显示API,比如:

  • @API表示一个开放的API,可以通过description简要描述该API的功能,一般和 Spring 的 @Controller一起。

  • 在一个@API下,可有多个@ApiOperation,表示针对该API的CRUD操作。在ApiOperation Annotation中可以通过value,notes描述该操作的作用,response描述正常情况下该请求的返回对象类型。

  • 在一个ApiOperation下,可以通过ApiResponses描述该API操作可能出现的异常情况。

  • @ApiParam用于描述该API操作接受的参数类型

  • @ApiModel用来描述封装的参数对象与返回的参数对象

  • @ApiModelProperty描述ApiModel的属性

PreviousSwaggerNextMaven

Last updated 5 years ago

Was this helpful?

最主要的是 swagger-springmvc 依赖,添加了它之后,我们可以使用 Swagger 特定的注解。Swagger 会查找自己的以及 Spring 特定的注解,这样项目部署后默认可以直接使用 获取所有WEB层的API接口。返回的是标志JSON格式,所以还要添加 Jckson 依赖。

这样其实就可以部署启动,然后直接访问获取所有通过 @Controller、@RequestMapping等注解配置的WEB接口。

Swagger 提供了一个静态项目 Swagger-ui,可以帮忙将获得的JSON格式的API优美的展示出来并且帮助测试这些接口。 集成 Swagger-ui 很简单,从 获取其所有的 dist 目录下东西放到需要集成的项目里,比如这里放入 src/main/webapp/WEB-INF/swagger-ui/ 目录下

重新部署启动后,访问 即可看到 Swagger-ui的界面。默认是从连接获取 API 的 JSON,不过可以在 Swagger-ui 的静态文件的 index.html 中配置为 。

http://host:port/projectName/api-docs
http://host:port/projectName/api-docs
https://github.com/swagger-api/swagger-ui
http://host:port/projectName/swagger/index.html
http://petstore.swagger.io/v2/swagger.json
http://host:port/projectName/api-docs