第05章—Swagger2打造在线接口文档

Posted 质行

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第05章—Swagger2打造在线接口文档相关的知识,希望对你有一定的参考价值。

spring boot 系列学习记录:http://www.cnblogs.com/jinxiaohang/p/8111057.html

码云源码地址:https://gitee.com/jinxiaohang/springboot

 

一、添加Swagger2依赖

 

<dependency><!--添加Swagger依赖 -->
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>
<dependency><!--添加Swagger-UI依赖 -->
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
</dependency>

 

二、添加配置

package com.xiaohang.springbootswagger2.config;

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.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * 主要用途:开启在线接口文档和添加相关配置
 */

@Configuration //标记配置类
@EnableSwagger2 //开启在线接口文档
public class Swagger2Config {
    /**
     * 添加摘要信息(Docket)
     */
    @Bean
    public Docket controllerApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .title("标题:jzh_用户信息管理系统_接口文档")
                        .description("描述:用于管理集团旗下公司的人员信息,具体包括XXX,XXX模块...")
                        .contact(new Contact("jzh", null, "191041707@qq.com"))
                        .version("版本号:1.0")
                        .build())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xiaohang.springbootswagger2.controller"))
                .paths(PathSelectors.any())
                .build();
    }
}

 

三、编写接口文档

  • @Api 描述类/接口的主要用途
  • @ApiOperation 描述方法用途
  • @ApiImplicitParam 描述方法的参数
  • @ApiImplicitParams 描述方法的参数(Multi-Params)
  • @ApiIgnore 忽略某类/方法/参数的文档

参考链接:http://blog.csdn.net/hj95815/article/details/78323766

Swagger2 使用注解来编写文档,只需要在控制层(controller)添加注解来描述接口信息即可。例如:

@Api("用户信息管理")
@RestController
@RequestMapping("/api/user/*")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("获取用户列表")
    @GetMapping("list")
    public List userList() {
        return userService.list();
    }

    @ApiOperation("获取单个用户")
    @ApiImplicitParam(paramType="query",name = "userId", value = "单个用户Id", dataType = "String")
    @GetMapping("list/{userId}")
    public User getOne(@RequestParam String userId){
        return userService.getOne(userId);
    }

    @ApiOperation("存储单个用户")
    @ApiImplicitParam(name = "user", value = "单个用户信息", dataType = "json")
    @PostMapping(value = "save")
    public String save(@RequestBody User user) {
        if (userService.save(user))
            return user.toString();
        return "{\\"msg\\":\\"error\\"}";
    }

    @ApiOperation("更新单个用户")
    @ApiImplicitParam(name = "user", value = "单个用户信息", dataType = "json")
    @PutMapping("update")
    public String update(@RequestBody User user) {
        if(userService.update(user))
            return user.toString();
        return "{\\"msg\\":\\"error\\"}";
    }

    @ApiOperation("删除单个用户")
    @ApiImplicitParam(paramType="query",name = "userId", value = "单个用户Id", dataType = "String")
    @DeleteMapping("delete/{userId}")
    public String delete(@RequestParam String userId) {
        if (userService.delete(userId))
            return "{\\"msg\\":\\"success\\"}";
        return "{\\"msg\\":\\"error\\"}";
    }
}

 

四、汉化(可跳过)

参考链接:https://www.jianshu.com/p/840320d431a1  https://www.jianshu.com/p/7e543f0f0bd8

 

1、添加自定义页面

在resourece目录下创建\\META-INF\\resourece目录,然后创建一个名称为"swagger-ui.html" 的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">![](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、添加配置

package com.xiaohang.springbootswagger2.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }


}

 

3、在启动类上添加注解@EnableWebMvc

五、查阅接口文档

打开http://localhost:8080/swagger-ui.html

效果如下:

 

六、测试接口

更新中...

以上是关于第05章—Swagger2打造在线接口文档的主要内容,如果未能解决你的问题,请参考以下文章

Spring-boot 之 Swagger2(打造不一样的api)

SpringBoot2.0系列教程Springboot框架添加Swagger2来在线自动生成接口的文档+测试功能

Swagger2 常用使用 及 SpringBoo 整合 Swagger2

接口文档生成工具Swagger2的使用

一分钟完成springboot项目整合Swagger2实现自动生成接口文档

springboot系列(十七):集成在线接口文档Swagger2|超级详细,建议收藏