假设我有两个不同的 API:A 和 B,它们获得相同的 POJO C。POJO C 有 2 个不同的字段 x 和 y。
public class C
{
String x;
String y;
}
是否可以设置一些条件验证注释,所以在将 POJO c 传递给 API A 时,只有字段 x 是必需的,而对于 API B,字段 x 和 y 都是必需的?
谢谢。
假设我有两个不同的 API:A 和 B,它们获得相同的 POJO C。POJO C 有 2 个不同的字段 x 和 y。
public class C
{
String x;
String y;
}
是否可以设置一些条件验证注释,所以在将 POJO c 传递给 API A 时,只有字段 x 是必需的,而对于 API B,字段 x 和 y 都是必需的?
谢谢。
最简单的方法是使用验证组。请试试 :
控制器 :
@RestController
public class FooController {
@PostMapping("/api1")
public Foo foo(@Validated(Api1Validated.class) Foo foo) {
return foo;
}
@PostMapping("/api2")
public Foo foo2(@Validated(Api2Validated.class) Foo foo) {
return foo;
}
}
域类:
@Data
public class Foo {
@NotEmpty(groups = {Api1Validated.class, Api2Validated.class})
private String name;
@NotNull(groups = {Api2Validated.class})
private Integer age;
}
验证接口:
public interface Api1Validated {
}
public interface Api2Validated {
}
单元测试 :
@SpringBootTest
@AutoConfigureMockMvc
public class FooControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@Test
public void test() throws Exception {
Foo foo = new Foo();
foo.setName("foo");
this.mockMvc.perform(post("/api1")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(foo)))
.andDo(print())
.andExpect(status().isOk());
this.mockMvc.perform(post("/api2")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(foo)))
.andDo(print())
.andExpect(status().isBadRequest());
}
}
版本:spring boot 2.3.4,junit 5.7.0
您可以对这种情况使用验证
例如 :-
import javax.validation.constraints.NotEmpty;
public class C {
@NotEmpty
String X;
String Y;
}
您还可以决定使用@NotEmpty 而不是@NotNull 来检查它是否不为空。
在控制器级别上,您可以使用以下内容:-
methodGet(@Valid @RequestBody final C c)
this methodGet = 控制器级方法