SpringBoot 集成 Swageer2

添加Maven依赖

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

添加配置类

package com.erp.server.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.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableSwagger2
@Configuration
public class SwaggerConfig {

    @Bean
    public Docket creatRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.erp.server.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("进销存系统")
                .description("这里是进销存系统的后台接口文档")
                //服务条款网址
                .termsOfServiceUrl("http://localhost:8080/swagger-ui.html")
                //联系人
                .contact(new Contact("wangbo","url地址", "email地址"))
                .version("1.0")
                .build();
    }

}

注解使用

@Api

用在请求类上,说明该类的作用。可以标记一个Controller类做为swagger文档资源。

value:url的路径值,在UI界面上也看到,可以不用配置。

String value() default "";

tags:说明该类的作用,可以在UI界面上看到的内容

String[] tags() default {""};

produces:配置返回数据类型,例如application/json,application/xml等

String produces() default "";

consumes:配置请求头,例如application/json,application/xml等

String protocols() default "";

authorizations:高级特性认证时配置

Authorization[] authorizations() default {@Authorization("")};

hidden:默认为false,配置为true将在文档中隐藏

boolean hidden() default false;

@ApiOperation

用在请求的方法上,说明方法的用途、作用

value:说明方法的用途、作用

String value();

notes:方法的备注说明

String notes() default "";

tags:

String[] tags() default {""};

response:返回的对象

Class<?> response() default Void.class;

responseContainer:这些对象是有效的List,Set,Map,其他是无效的

String responseContainer() default "";

responseReference:

String responseReference() default "";

httpMethod:可以配置其中HTTP请求方式

String httpMethod() default "";

nickname:

String nickname() default "";

produces:配置返回数据类型,例如application/json,application/xml等

String produces() default "";

consumes:配置请求头,例如application/json,application/xml等

String consumes() default "";

protocols:

String protocols() default "";

authorizations:高级特性认证时配置

Authorization[] authorizations() default {@Authorization("")};

hidden:默认为false,配置为true将在文档中隐藏

boolean hidden() default false;

responseHeaders:配置响应头

ResponseHeader[] responseHeaders() default {@ResponseHeader(
    name = "",
    response = Void.class
)};

code:HTTP的状态码,默认200

int code() default 200;

extensions:扩展属性

Extension[] extensions() default {@Extension(
    properties = {@ExtensionProperty(
    name = "",
    value = ""
)}
)};

@ApiImplicitParams

用在请求的方法上,表示一组参数说明,里面通过ApiImplicitParam配置具体参数。

public @interface ApiImplicitParams {
    ApiImplicitParam[] value();
}

@ApiImplicitParam

用在请求的方法上,表示单个参数说明;或者用在@ApiImplicitParams注解中,指定一个请求参数的各个方面

name:参数名

String name() default "";

value:参数说明解释

String value() default "";

defaultValue:参数的默认值

String defaultValue() default "";

allowableValues:

String allowableValues() default "";

required:参数是否必传 true | false,默认false

boolean required() default false;

access:

String access() default "";

allowMultiple:

boolean allowMultiple() default false;

dataType:参数类型,默认String,只作为标志说明,不做实际验证,String和Long

String dataType() default "";

dataTypeClass:

Class<?> dataTypeClass() default Void.class;

paramType:查询参数位置

  header:请求参数放置于 Header,使用@RequestHeader获取

  query:请求参数放置于请求地址后边,使用@RequestParam获取

  path:请求参数放置于请求地址路径中,使用@PathVariable获取

  body:以流的形式提交参数,仅支持POST

  form:以form表单的形式提交参数,仅支持POST

String paramType() default "";

example:

String example() default "";

examples:

Example examples() default @Example({@ExampleProperty(
    mediaType = "",
    value = ""
)});

type:

String type() default "";

format:

String format() default "";

allowEmptyValue:

boolean allowEmptyValue() default false;

readOnly:

boolean readOnly() default false;

collectionFormat:

String collectionFormat() default "";

@ApiParam

public @interface ApiParam {
    String name() default "";

    String value() default "";

    String defaultValue() default "";

    String allowableValues() default "";

    boolean required() default false;

    String access() default "";

    boolean allowMultiple() default false;

    boolean hidden() default false;

    String example() default "";

    Example examples() default @Example({@ExampleProperty(
      mediaType = "",
      value = ""
   )});

    String type() default "";

    String format() default "";

    boolean allowEmptyValue() default false;

    boolean readOnly() default false;

    String collectionFormat() default "";
}

@ApiModel

一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候,用于对类进行说明,描述一个Model的信息,表示参数用实体类接收。

public @interface ApiModel {
    String value() default "";

    String description() default "";

    Class<?> parent() default Void.class;

    String discriminator() default "";

    Class<?>[] subTypes() default {};

    String reference() default "";
}

@ApiModelProperty

注解用于方法、字段,表示对model属性的说明或者数据操作更改,配合ApiModel一起使用。

public @interface ApiModelProperty {
    String value() default "";

    String name() default "";

    String allowableValues() default "";

    String access() default "";

    String notes() default "";

    String dataType() default "";

    boolean required() default false;

    int position() default 0;

    boolean hidden() default false;

    String example() default "";

    boolean readOnly() default false;

    String reference() default "";

    boolean allowEmptyValue() default false;
}

@ApiResponses

用在请求的方法上,表示一组响应

public @interface ApiResponses {
    ApiResponse[] value();
}

@ApiResponse

用在@ApiResponses中,一般用于表达一个错误的响应信息

public @interface ApiResponse {
    int code();

    String message();

    Class<?> response() default Void.class;

    String reference() default "";

    ResponseHeader[] responseHeaders() default {@ResponseHeader(
      name = "",
      response = Void.class
  )};

    String responseContainer() default "";
}

@ApiIgnore

用在Controller类或者接口方法上,表示该类或者接口被忽略,不在接口文档显示

public @interface ApiIgnore {
  //简要说明为何忽略此参数/操作
  String value() default "";
}

问题

目前了解到的是Swagger不支持直接获取JSONObject和Map类型的参数,这种参数内部字段不可知,文档显示不出来

如果不想封装为一个Model的话可以参考下面的博客实现下,自定义一个注解。

https://blog.csdn.net/cy921107/article/details/82761575 JSONObject

https://blog.csdn.net/hellopeng1/article/details/82227942 Map

示例

package com.erp.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.erp.server.model.User;
import com.erp.server.service.TestService;
import com.erp.server.utils.Constants;
import com.erp.server.utils.result.ResultBuilder;
import com.erp.server.utils.result.StatusCode;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;


@Api(tags = {"测试接口类"})
@RestController
@RequestMapping(value = "/api/test")
public class TestController {

    private static final Logger logger = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private TestService testService;
    @ApiIgnore
    @ApiOperation(value = "测试Hello", notes = "一个测试的hello接口")
    @GetMapping("/hello")
    public String hello(){
        return  "Hello Spring Boot";
    }

    @ApiOperation(value = "查询用户", notes = "根据ID查询用户")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "path", dataType = "integer")
    @GetMapping("/user/{id}")
    public ResultBuilder<User> user(@PathVariable("id")Integer id){
        User user = testService.getUserById(id);
        return new ResultBuilder<User>(user, StatusCode.SUCCESS);
    }

    @ApiOperation(value = "查询用户", notes = "根据ID和姓名查询用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户凭证", required = true, paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "query", dataType = "integer"),
            @ApiImplicitParam(name = "name", value = "用户名", required = true, paramType = "query", dataType = "String")
    })
    @GetMapping("/user/id/name")
    public ResultBuilder<User> user1(@RequestHeader("token")String token,
                                     @RequestParam("id")Integer id,
                                     @RequestParam("name")String name){
        logger.debug("token:{},id:{},name:{}", token, id, name);
        User user = testService.getUserById(id);
        return new ResultBuilder<User>(user, StatusCode.SUCCESS);
    }

    @ApiOperation(value = "添加用户", notes = "使用JSON数据添加用户")
    @ApiImplicitParam(name = "jsonObject", value = "用户数据", required = true, paramType = "body",
       examples = @Example(value = @ExampleProperty(mediaType = "application/json", value = "{'id':'','name':'','age':''}"))
            )
    @PostMapping("/user/add/")
    public ResultBuilder<User> adduser(@RequestBody JSONObject jsonObject){
        logger.debug(jsonObject.toJSONString());
        Integer id = jsonObject.getInteger("id");
        User user = testService.getUserById(id);
        return new ResultBuilder<User>(user, StatusCode.SUCCESS);
    }

    @ApiOperation(value = "添加用户", notes = "使用对象数据添加用户")
    @ApiImplicitParam(name = "user", value = "用户数据", required = true, paramType = "body", dataType = "User")
    @PostMapping("/user/add1/")
    public ResultBuilder<User> adduser1(@RequestHeader(Constants.ACCEPT_VERSION)String acceptVersion,
                                        @RequestBody User user){
        return new ResultBuilder<User>(null, StatusCode.SUCCESS);
    }

}

@Api 使用示例

属性注释

@Api  使用在接口类上

  tags  说明该类的作用,可以在UI界面上看到的内容

示例代码

@Api(tags = {"版本接口类"})
@RestController
@RequestMapping("/api/version")
public class VersionController {
  ......  
}

界面显示

@ApiOperation 和 @ApiImplicitParam 使用示例

属性注释

@ApiOperation  使用在接口方法上

  value  接口名

  notes  接口注释米描述

@ApiImplicitParams  表示多个参数的情况,需@ApiImplicitParam配合使用

@ApiImplicitParam  表示单个参数

  name  参数

  value  参数描述

  required  参数是否必须,默认false

  dataType  参数类型,这个一般还是别写了,经常写了导致无法使用

  paramType  参数位置  

    header:请求参数放置于 Header,使用@RequestHeader获取

    query:请求参数放置于请求地址后边,使用@RequestParam获取

    path:请求参数放置于请求地址路径中,使用@PathVariable获取

    body:以流的形式提交参数,仅支持POST

    form:以form表单的形式提交参数,仅支持POST

示例代码

    @ApiOperation(value = "采购单列表", notes = "用于查询采购单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询的页码,默认1", required = false, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数,默认10", required = false, paramType = "query"),
            @ApiImplicitParam(name = "wareId", value = "采购ID", required = false, paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间,毫秒数", required = false, paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间,毫秒数", required = false, paramType = "query"),
            @ApiImplicitParam(name = "wareStatus", value = "采购单状态。-1:删除,0:正常", required = false, paramType = "query"),
            @ApiImplicitParam(name = "wareType", value = "采购类型:0:入库单,1:退货单", required = false, paramType = "query")
    })
    @GetMapping("/list")
    public ResultBuilder getWareHouseList(@RequestHeader(Constants.VERSION_CODE)Integer versionCode,
                                          @RequestHeader(Constants.ACCESS_TOKEN)String token,
                                          @RequestParam(value = "pageNum", required = false)Integer pageNum,
                                          @RequestParam(value = "pageSize", required = false)Integer pageSize,
                                          @RequestParam(value = "wareId", required = false)String wareId,
                                          @RequestParam(value = "startTime", required = false)Long startTime,
                                          @RequestParam(value = "endTime", required = false)Long endTime,
                                          @RequestParam(value = "wareStatus", required = false)Integer wareStatus,
                                          @RequestParam(value = "wareType", required = false)Integer wareType){
        return wareHouseService.getWareHouseList(pageNum, pageSize, wareId, startTime, endTime, wareStatus, wareType);
    }

界面显示

@ApiModel 和 @ApiModelProperty 使用示例

属性注释

@ApiModel 使用在实体类上

  value  实体类名称

  description  实体类描述信息

@ApiModelProperty 使用在实体类中字段上

  value  字段名

  required   字段是否必须,默认false

  hide  字段是否隐藏,默认false

  example  字段值示例

示例代码

实体类

@ApiModel(value = "软件版本", description = "这里是描述信息")
public class Version {
    @ApiModelProperty(value = "版本", required = true, example = "1.0.0")
    private String version;
    @ApiModelProperty(value = "版本号", required = true)
    private Integer versionCode;
    @ApiModelProperty(value = "最小版本号", required = true)
    private Integer minVersionCode;
    @ApiModelProperty(value = "强制更新标志", required = true)
    private Integer updateForce;
    @ApiModelProperty(value = "更新内容")
    private String updateContent;
    @ApiModelProperty(value = "更新地址", required = true)
    private String updateUrl;
    @ApiModelProperty(hidden = true)
    private Date createTime;
    @ApiModelProperty(hidden = true)
    private Date updateTime;
    省略set/get
}

接口方法

@ApiOperation(value = "新版本检查", notes = "检查APP是否需要进行版本升级")
@PostMapping("/check")
public ResultBuilder versionCheck(@RequestBody Version version){
  。。。
}

界面显示

Models中也会显示这个Model

 

posted @ 2019-04-01 23:27  一线大码  Views(1059)  Comments(0Edit  收藏  举报