什么是Swagger

简单来说,Swagger是一个规范了整个开发周期的AIPI文档生成框架(Swagger is the world’s largest framework of API developer tools for the OpenAPI Specification(OAS), enabling development across the entire API lifecycle, from design and documentation, to test and deployment)。使用Swagger可以直接生成API的说明文档。
以 Spring Boot学习日志(四)使用Mybatis的内容为例,经过简单的配置,Swagger自动生成的API文档样式如下:

Swagger配置步骤

1, 在 Spring Boot学习日志(四)使用Mybatis的基础上,添加如下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>

2,在MybatisDemoApplication的同级目录下,创建Swagger的配置文件

@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket controllerApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .title("Swagger测试文档")
                        .description("后台接口说明.")
                        .contact(new Contact("azui007", "", null))
                        .version("版本号:1.0")
                        .build())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.mybatis_demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }
}

Configuration表示该类是配置文件。

@EnableSwagger2表示启用Swagger2

select()返回一个ApiSelectorBuilder用来控制Swagger显示的接口范围,这里设置为controller包内所有类。

启动项目代码:

基于spring boot的系统接口设计 springboot接口管理_Swagger

添加说明

进过上述简单的配置之后,Swagger的基本功能就可以用了,但是使用体验欠佳,比如传递过去的参数不知道是什么意思(如下图所示 ) ,不知道哪些参数必填之类的问题就显示了出来,接下来记录如何解决这些问题。

基于spring boot的系统接口设计 springboot接口管理_Spring Boot_02


1,添加参数说明

在Entity类中,可以使用@ApiModelProperty添加属性意义的解释说明,使用@ApiParam标识该属性是否为必须输入项。

@ApiParam(required=true)
    @ApiModelProperty(value="主键",name="id")
    private Integer id;
    @ApiModelProperty(value="用户名",name="userName")
    private String userName;

    @ApiModelProperty(value="用户组",name="groupid")
    private Integer groupid;

2,添加接口说明
使用@ApiOperation添加接口意义说明,使用@RequestParam添加接口方法参数说明。

@ApiOperation("得到用户列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Object queryUser(@RequestParam(value = "页数", required = false, defaultValue = "1") Integer pageNum,
                            @RequestParam(value = "每页显示数量", required = false, defaultValue = "10") Integer pageSize, User user) {
        return mapper.queryUser(user);
    }

    @ApiOperation("添加新用户")
    @RequestMapping(value = "/insert", method = RequestMethod.GET)
    public Object insertUser(User user) {
        return mapper.insertUser(user);
    }

    @ApiOperation("更新用户信息")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public Object updateUser(User user) {
        return mapper.updateUser(user);
    }

    @ApiOperation("删除用户信息")
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public Object deleteUser(User user) {
        return mapper.deleteUser(user);
    }

运行效果如下:

基于spring boot的系统接口设计 springboot接口管理_javascript_03


基于spring boot的系统接口设计 springboot接口管理_Spring Boot_04


这里把上面设置的参数的意义,参数是否必须输入以及参数的默认值都显示了出来。

Swagger 汉化

英文的界面已经很清爽了,但是如果是汉语版的就更好了。
那么Swagger如何汉化呢?
1,在resources目录下新建文件夹META-INF\resources,新建swagger-ui.html,将以下内容拷贝进swagger-ui.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Swagger UI</title>
    <link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-32x32.png" sizes="32x32"/>
    <link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-16x16.png" sizes="16x16"/>
    <link href='webjars/springfox-swagger-ui/css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/reset.css' media='print' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/print.css' media='print' rel='stylesheet' type='text/css'/>

    <script src='webjars/springfox-swagger-ui/lib/object-assign-pollyfill.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery.slideto.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/handlebars-4.0.5.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/lodash.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/backbone-min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/swagger-ui.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack_extended.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jsoneditor.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/marked.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/swagger-oauth.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/springfox.js' type='text/javascript'></script>

    <!--国际化操作:选择中文版 -->
    <script src='webjars/springfox-swagger-ui/lang/translator.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lang/zh-cn.js' type='text/javascript'></script>

</head>

<body class="swagger-section">
<div id='header'>
    <div class="swagger-ui-wrap">
        <a id="logo" href="http://swagger.io"><img class="logo__img" alt="swagger" height="30" width="30" src="webjars/springfox-swagger-ui/images/logo_small.png" /><span class="logo__title">swagger</span></a>
        <form id='api_selector'>
            <div class='input'>
                <select id="select_baseUrl" name="select_baseUrl"></select>
            </div>
            <div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
            <div id='auth_container'></div>
            <div class='input'><a id="explore" class="header__btn" href="#" data-sw-translate>Explore</a></div>
        </form>
    </div>
</div>

<div id="message-bar" class="swagger-ui-wrap" data-sw-translate> </div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>

2,在resources内创建webjars\springfox-swagger-ui\lang文件夹,并在lang文件夹内创建zh-cn.js,内容如下:

'use strict';

/* jshint quotmark: double */
window.SwaggerTranslator.learn({
    "Warning: Deprecated":"警告:已过时",
    "Implementation Notes":"实现备注",
    "Response Class":"响应类",
    "Status":"状态",
    "Parameters":"参数",
    "Parameter":"参数",
    "Value":"值",
    "Description":"描述",
    "Parameter Type":"参数类型",
    "Data Type":"数据类型",
    "Response Messages":"响应消息",
    "HTTP Status Code":"HTTP状态码",
    "Reason":"原因",
    "Response Model":"响应模型",
    "Request URL":"请求URL",
    "Response Body":"响应体",
    "Response Code":"响应码",
    "Response Headers":"响应头",
    "Hide Response":"隐藏响应",
    "Headers":"头",
    "Try it out!":"试一下!",
    "Show/Hide":"显示/隐藏",
    "List Operations":"显示列表",
    "Expand Operations":"展开操作",
    "Raw":"原始",
    "can't parse JSON.  Raw result":"无法解析JSON. 原始结果",
    "Example Value":"示例",
    "Click to set as parameter value":"点击设置参数",
    "Model Schema":"模型架构",
    "Model":"模型",
    "apply":"应用",
    "Username":"用户名",
    "Password":"密码",
    "Terms of service":"服务条款",
    "Created by":"创建者",
    "See more at":"查看更多:",
    "Contact the developer":"联系开发者",
    "api version":"api版本",
    "Response Content Type":"响应Content Type",
    "Parameter content type:":"参数类型:",
    "fetching resource":"正在获取资源",
    "fetching resource list":"正在获取资源列表",
    "Explore":"浏览",
    "Show Swagger Petstore Example Apis":"显示 Swagger Petstore 示例 Apis",
    "Can't read from server.  It may not have the appropriate access-control-origin settings.":"无法从服务器读取。可能没有正确设置access-control-origin。",
    "Please specify the protocol for":"请指定协议:",
    "Can't read swagger JSON from":"无法读取swagger JSON于",
    "Finished Loading Resource Information. Rendering Swagger UI":"已加载资源信息。正在渲染Swagger UI",
    "Unable to read api":"无法读取api",
    "from path":"从路径",
    "server returned":"服务器返回"
});

运行结果如下:

基于spring boot的系统接口设计 springboot接口管理_spring_05


下载地址;https://pan.baidu.com/s/1jJbpbVK