搬砖小抄

lombok accessors 注解导致swagger文档异常

字数统计: 362阅读时长: 1 min
2020/12/21 Share

前几天在项目中使用swagger时发现一个诡异的问题,后来发现是同时使用了@Accessors(chain = true)@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)这两个注解引起的。

问题如图,password这个字段被识别成了一个对象

一时找不出原因,于是我搭建了一个简单的项目来试错,结果发现这两个注解只要不同时使用,就没有问题,实验关键代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
@Data
@Accessors(chain = true)
@NoArgsConstructor
public class UserA implements Serializable {

private static final long serialVersionUID = 1L;

@Schema(description = "username", example = "john")
@Size(min = 6, max = 20, groups = { Groups.Default.class })
private String username;


@Schema(description = "password", example = "acb123", accessMode = Schema.AccessMode.WRITE_ONLY)
@NotNull(groups = { Groups.Default.class })
@Size(min = 6, max = 20, groups = { Groups.Default.class })
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
}


@Data
//@Accessors(chain = true)
@NoArgsConstructor
public class UserB implements Serializable {

private static final long serialVersionUID = 1L;

@Schema(description = "username", example = "john")
@Size(min = 6, max = 20, groups = { Groups.Default.class })
private String username;


@Schema(description = "password", example = "acb123", accessMode = Schema.AccessMode.WRITE_ONLY)
@NotNull(groups = { Groups.Default.class })
@Size(min = 6, max = 20, groups = { Groups.Default.class })
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
}

由于使用了lombok,所以去看了一下最后生成的代码(UserA),发现有以下代码

1
2
3
4
5
6
7
8
9
10
11
12
13

@JsonProperty(
access = Access.WRITE_ONLY
)
private String password;

@JsonProperty(
access = Access.WRITE_ONLY
)
public UserA setPassword(final String password) {
this.password = password;
return this;
}

所以问题就清楚了,实际使用中发现如果使用了knife4j的UI,password还会被显示为嵌套对象。

CATALOG