SpringFox - 在 Swagger-ui 中隐藏调用端点不需要的某些字段 [英] SpringFox - Hide certain fields in Swagger-ui that aren't required for the call to an endpoint

查看:32
本文介绍了SpringFox - 在 Swagger-ui 中隐藏调用端点不需要的某些字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何方法可以让 SpringFox 不显示在调用特定端点时不需要的某个实体的所有字段.

I would like to know if there is any way of making SpringFox to not show all the fields of a certain entity that aren't required in the call to an specific endpoint.

例如:

具有以下实体:

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 端点中只需要名称和轮子,但在文档中 Swagger-ui 显示所有字段,就好像它们是必需的一样.我已经尝试过 @JsonViews 但 Springfox 还没有处理它们.

The thing is that in the create Car endpoint only name and wheels are required, but in the documentation Swagger-ui shows all the fields as if they were required. I've already tried @JsonViews but Springfox does not handle them yet.

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

Is there any way to avoid this?

推荐答案

使用@ApiModelProperty(来自io.swagger.annotations)

  • 通过required,您可以定义该属性是必需的还是可选的.
  • 使用 hidden,您可以在 Swagger UI 中隐藏该属性,但是如果设置了该属性,它无论如何都会返回.
  • With required you define whether the property is mandatory or optional.
  • With hidden you can hide the property in Swagger UI, however if it's set it is returned anyway.

例如:

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 端点文档中的属性也将被隐藏(请记住这一点).如果您不想要这种行为,请使用单独的模型.

Since you use the same model for request and response (with the example above) the attributes in the documentation for GET endpoint will be also hidden (keep that in mind). If you don't want such behaviour then use separate models.

这篇关于SpringFox - 在 Swagger-ui 中隐藏调用端点不需要的某些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆