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.
相关文章