SpringFox - 隐藏 Swagger-ui 中调用端点不需要的某些字段

2023-12-20

我想知道是否有任何方法可以使 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);
}

问题是,在 create Car 端点中仅需要名称和车轮,但在文档 Swagger-ui 中显示所有字段,就好像它们是必需的一样。我已经尝试过了@JsonViews但 Springfox 还没有处理它们。

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


Use the @ApiModelProperty (from io.swagger.annotations)

  • With required您可以定义该属性是强制的还是可选的。
  • With hidden您可以在 Swagger UI 中隐藏该属性,但如果设置了该属性,无论如何都会返回该属性。

例如:

public class Car {

    @ApiModelProperty(value = "id", required = true)
    long id;

    @ApiModelProperty(value = "wheels", required = true)
    int wheels;

    @ApiModelProperty(value = "name", hidden = true)
    String name;

    @ApiModelProperty(value = "type", hidden = true)
    String type;

    @ApiModelProperty(value = "canFly", hidden = true)
    boolean canFly;
}

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringFox - 隐藏 Swagger-ui 中调用端点不需要的某些字段 的相关文章

随机推荐