Spring MVC Swagger在线文档生成

说明:
    如果你在为一个系统设计API,你希望更好的管理你的API,你希望有一个工具能一站式地解决API相关的所有事情,从设计到文档再到mock,甚至能直接从设计文档中生成代码(声明式编程),这确实是可能的,如果你的描述信息是完备的,自动化生成mock接口以及具体语言(诸如swagger支持flask等十几种框架)实现在理论上都可行。

Swagger作用:
1.接口的文档在线自动生成;
2.功能测试;

    

Swagger其中主要要项目如下:
1.Swagger-tools:提供各种与Swagger进行集成和交互的工具。例如模式检验、Swagger 1.2文档转换成Swagger 2.0文档等功能。
2.Swagger-core: 用于Java/Scala的的Swagger实现。与JAX-RS(Jersey、Resteasy、CXF...)、Servlets和Play框架进行集成。
3.Swagger-js: 用于JavaScript的Swagger实现。
4.Swagger-node-express: Swagger模块,用于node.js的Express web应用框架。
5.Swagger-ui:一个无依赖的HTML、JS和CSS集合,可以为Swagger兼容API动态生成优雅文档。
6.Swagger-codegen:一个模板驱动引擎,通过分析用户Swagger资源声明以各种语言生成客户端代码。


官网:
https://swagger.io/tools/swagger-ui/

官网demo:
https://petstore.swagger.io/?_ga=2.238614403.2017989660.1532660198-1097460747.1532660198


以下是Spring MVC结合Swagger实现API文档在线自动生成示例:
一、Spring Mvc配置:
1)配置Maven引用:

<!-- swagger -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>

2)spring配置:
在mvc的基础上增加

<mvc:default-servlet-handler/>

主要用于swagger静态文件访问,当然如果已有,可以忽略;

3)Controller配置:

package com.sam.controller;

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 org.springframework.web.bind.annotation.ResponseBody;

import com.sam.model.User;

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

/**
 * @ClassName: ApiController
 * @Description: test
 * @author sam
 * @date 2018-07-27 14:06:18
 */
@Api(value = "API Controller", tags = { "用户管理" })
@Controller
@RequestMapping("/api")
public class ApiController {

    @ApiOperation(value = "获取用户信息", notes = "注意问题点")
    @ApiResponses({ 
            @ApiResponse(code = 200, message = "操作成功"), 
            @ApiResponse(code = 500, message = "服务器内部异常"),
            @ApiResponse(code = 403, message = "权限不足") })
    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    @ResponseBody
    public String getUser(@ApiParam(required = true, name = "start", value = "开始索引") Integer start,
            @ApiParam(required = true, name = "limit", value = "每页行数") Integer limit,
            @ApiParam(required = false, name = "userName", value = "名称模糊查询") String userName) {
        return "user";
    }

    @ApiOperation(value = "删除用户", notes = "删除用户为伪删除!")
    @ApiResponses({ 
            @ApiResponse(code = 200, message = "操作成功"), 
            @ApiResponse(code = 500, message = "服务器内部异常"),
            @ApiResponse(code = 403, message = "权限不足") })
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "Long", name = "id", value = "信息id", required = true) })
    @RequestMapping(value = "/deleteUser", method = RequestMethod.GET)
    @ResponseBody
    public String deleteUser(Long id) {
        return "user";
    }

    @ApiOperation("更改用户信息")
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    public int updateUser(@RequestBody  @ApiParam(name = "用户对象", value = "传入json格式", required = true) User user) {
        return 1;
    }

}

其它业务实体model:

package com.sam.model;

import java.io.Serializable;
import java.util.List;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel(value = "user对象", description = "用户对象user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;
    @ApiModelProperty(value = "用户名", name = "username", example = "admin")
    private String username;
    @ApiModelProperty(value = "状态", name = "state", required = true)
    private Integer state;
    private String password;
    private String nickName;
    private Integer isDeleted;

    @ApiModelProperty(value = "id数组", hidden = true)
    private String[] ids;
    private List<String> idList;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public Integer getIsDeleted() {
        return isDeleted;
    }

    public void setIsDeleted(Integer isDeleted) {
        this.isDeleted = isDeleted;
    }

    public String[] getIds() {
        return ids;
    }

    public void setIds(String[] ids) {
        this.ids = ids;
    }

    public List<String> getIdList() {
        return idList;
    }

    public void setIdList(List<String> idList) {
        this.idList = idList;
    }

}

Swagger代码:

package com.sam.swagger;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import springfox.documentation.service.ApiInfo;
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
@ComponentScan(basePackages = {"com.sam.controller"})   
@EnableWebMvc
public class SwaggerConfig extends WebMvcConfigurationSupport {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        Contact contact = new Contact("admin", "https://www.baidu.com", "[email protected]");
        return new ApiInfo("平台开放API接口",//大标题 title
                "Swagger",//小标题
                "0.0.1",//版本
                "www.baidu.com",//termsOfServiceUrl
                contact,//作者
                "Blog",//链接显示文字
                "https://www.baidu.com"//网站链接
        );
    }
    
      
}

5)swagger静态资源配置:
下载地址:https://github.com/swagger-api/swagger-ui
下载之后将dist目录下文件拷贝到webapp下的swagger目录中,没有swagger目录则创建。

然后修改index.html,修改swagger生成的json数据地址,如下:

以上配置完成后,启动spring mvc项目工程,可以生成在线接口文档
访问swagger项目(自个项目名称叫做swagger)下刚拷贝的swagger目录下index.html,即可看到相应的文档生成,
如下:http://localhost:8085/swagger/swagger/index.html

可以查看到Json数据地址:http://localhost:8085/swagger/v2/api-docs.do

三、Swagger进行调用测试
Swagger除了生成接口文档之外,还可以直接进行接口调用,如下:


选择Try it out,然后输入相应的参数点击Execute即可调用接口并返回相应的结果!


四、Swagger常用注解说明: 
- @Api()用于类, 表示标识这个类是swagger的资源 
字段说明:
tags–表示分组
value–类的描述 

- @ApiOperation()用于方法,表示一个http请求的操作 
字段说明:
value用于方法描述 
notes用于提示内容 
tags可以重新分组(视情况而用)

- @ApiParam()用于方法,参数,表示对参数的添加元数据(说明或是否必填等)
字段说明:
name–参数名 
value–参数说明 
required–是否必填

- @ApiModel()用于类 
表示对类进行说明,用于参数用实体类接收 

字段说明:
value–表示对象名 
description–描述 

- @ApiModelProperty()用于方法,字段,表示对model属性的说明或者数据操作更改 
字段说明:
value–字段说明 
name–重写属性名字 
dataType–重写属性类型 
required–是否必填 
example–举例说明 
hidden–隐藏

- @ApiResponses:通常用来包含接口的一组响应注解,可以简单的理解为响应注解的集合声明;
  @ApiResponse:用在@ApiResponses中,一般用于表达一个响应信息
字段说明:
code:即httpCode,例如400 
message:信息,例如"操作成功"
response = UserVo.class  这里UserVo是一个配置了@ApiModel注解的对像,该是对像属性已配置 @ApiModelProperty,swagger可以通过这些配置,生 成接口返回值


- @ApiIgnore()用于类,方法,方法参数 
表示这个方法或者类被忽略 

- @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam 用于方法[表示单独的请求参数]
字段说明:
name–参数ming 
value–参数说明 
dataType–数据类型 
paramType–参数类型 
example–举例说明

备注:
@ApiImplicitParams和@ApiParam都可以描述参数,但是有所不同:
ApiImplicitParam 与 ApiParam 的区别
ApiImplicitParam: This is the only way to define parameters when using Servlets or other non-JAX-RS environments.

对Servlets或者非 JAX-RS的环境,只能使用 ApiImplicitParam。
在使用上,ApiImplicitParam比ApiParam具有更少的代码侵入性,只要写在方法上就可以了,但是需要提供具体的属性才能配合swagger ui解析使用。
ApiParam只需要较少的属性,与swagger ui配合更好。


    
    

猜你喜欢

转载自blog.csdn.net/vtopqx/article/details/81236531