@Path("/user")
@Produces({"application/json", "application/xml"})
public class HiddenAnnotatedUserResourceMethodAndData {
UserData userData = new UserData();
@POST
@Hidden
@Operation(summary = "Create user",
description = "This can only be done by the logged in user.")
@Path("/1")
public Response createUser(
@Parameter(description = "Created user object", required = true) User user) {
userData.addUser(user);
return Response.ok().entity("").build();
}
@POST
@Operation(summary = "Create user",
description = "This can only be done by the logged in user.")
@Path("/2")
public Response createUserWithHiddenBeanProperty(
@Parameter(description = "Created user object", required = true) UserResourceBean user) {
return Response.ok().entity("").build();
}
}
以上输出
openapi: 3.0.1
paths:
/user/2:
post:
summary: Create user
description: This can only be done by the logged in user.
operationId: createUserWithHiddenBeanProperty
requestBody:
description: Created user object
content:
'*/*':
schema:
$ref: '#/components/schemas/UserResourceBean'
required: true
responses:
default:
description: default response
components:
schemas:
UserResourceBean:
type: object
properties:
foo:
type: string
public class UserVo {
@JsonIgnoreProperties("password")
public static class Public extends User {}
@JsonIgnoreProperties("userId")
public static class Save extends User {}
@JsonIgnoreProperties("password")
public static class Update extends User {}
}
实体🏻类:
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer userId;
// 🚨 Write only access to password default in entity
// in order to hide it for update case we will extends class behaviour
// in our custom views
// Instead of JsonViews i use custom views (i.e UserVo) with JsonProperty
// @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@NotBlank
@Schema(example = "lorem1234")
@Column(name = "password")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
.....
}
控制🏻器类:
// See UserVo.Save in request body it serialize this class
@PostMapping(value = "/create")
public ResponseModel<User> createUser(@Valid @RequestBody UserVo.Save user) {
// ... My dirty code comes here 🤡
}
5条答案
按热度按时间i1icjdpr1#
要在Swagger API v2中隐藏请求字段:
在OpenAPI v3中:
4dc9hkyq2#
另请参阅:https://github.com/springfox/springfox/issues/2816
gzszwxb43#
可以将@Hidden与Swagger Core 2.X一起使用
@隐藏--隐藏资源、操作或属性
上述链接的示例:将指定的资源、类别或Bean类型标记为隐藏,阅读/解析时略过。
以上输出
ogq8wdun4#
通常在这种情况下使用DTO会很有用,为每个实体定义一个DTO(这取决于您的项目,但大多数情况下可能很有用),然后使用Mapstruct将您的实体Map到DTO,反之亦然,然后在您的DTO类中,通过在您想要的每个字段上使用@JsonIgnorProperties注解,您可以省略该字段,使其不被API服务公开。
zte4gxcn5#
扩展🏻您的实体并使用@JsonIgnoreProperties
实体🏻类:
控制🏻器类:
结果🏻: