SpringFox-在Swagger-ui中隐藏呼叫端点不需要的某些字段

时间:2019-02-08 15:25:24

标签: java spring swagger swagger-ui springfox

我想知道是否有某种方法可以使SpringFox不显示特定实体的所有字段,而这些字段在调用特定端点时不是必需的。

例如:

具有以下实体:

public class Car {
    long id;
    String name;
    int wheels;
    String type;
    boolean canFly;
}

以及以下端点:

@RequestMapping(method = RequestMethod.GET,
                produces = MediaType.APPLICATION_JSON_VALUE)
public Car get(@RequestParam(value = "carId", required = true) long projectId) {
    return carService.get(carId);
}

@RequestMapping(method = RequestMethod.POST,
                consumes = MediaType.APPLICATION_JSON_VALUE,
                produces = MediaType.APPLICATION_JSON_VALUE)
public Car create(@RequestBody Car car) {
    return carService.create(car);
}

@RequestMapping(method = RequestMethod.PUT,
                consumes = MediaType.APPLICATION_JSON_VALUE,
                produces = MediaType.APPLICATION_JSON_VALUE)
public Car update(@RequestBody Car car) {
    return carService.update(car);
}

问题在于,在创建Car端点时,仅需要名称和wheel,但是在文档Swagger-ui中,所有字段均显示为必填字段。我已经尝试过@JsonViews,但Springfox尚未处理它们。

有什么办法可以避免这种情况?

2 个答案:

答案 0 :(得分:0)

使用<cache name = "TestEntity" maxElementsInMemory="100" eternal="false" timeToLiveSeconds="60" memoryStoreEvictionPolicy="LRU"> </cache> (来自@ApiModelProperty

  • 使用io.swagger.annotations,您可以定义该属性是必选属性还是可选属性。
  • 使用required,您可以在Swagger UI中隐藏该属性,但是如果设置,则无论如何都会返回该属性。

例如:

hidden

由于您对请求和响应使用相同的模型(如上例所示),GET端点文档中的属性也将被隐藏(请记住这一点)。如果您不希望出现这种情况,请使用单独的模型。

答案 1 :(得分:0)

从springfox-boot-starter 3.0.0开始

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>

通过在需要的字段上添加Jackson JsonProperty批注,可以非常轻松,高效地完成此任务。

@JsonProperty(access = JsonProperty.Access.READ_ONLY)

例如您有一个模型类Client,并且都想要:

  • 隐藏请求中的字段ID(例如POST和PUT),但在响应中显示
  • 不接受控制器中的字段ID(因此无论设置哪个调用方,该字段ID始终为0),但应在响应中返回客户端的ID值。

您可以通过在id字段上添加注释来实现这些目的

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class Client {
    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private long id;
    private String name;
}