Spring 框架验证响应数据
Spring framework validate response data
我有自定义的简单端点,returns 一些对象(在我的案例中记录)。我想验证返回的输出数据的正确性(例如,输出 DTO 确实将所有字段设置为非空值)。
执行此类验证的最佳位置在哪里?
是否可以更正验证器中的返回值(例如,将字段“上次访问资源”的值 null 更改为“尚未访问资源”)
示例说明代码:
public record SomeDTO(String nameOfUser, String lastAccessedInfo, List<SomeDTO> recursiveIsFun) {
}
@GetMapping(value = "/somethingEndpoint", produces = MediaType.APPLICATION_JSON_VALUE)
public SomeDTO getSomething(HttpServletRequest request) throws IOException, InterruptedException {
final String baseUrl = ServletUriComponentsBuilder.fromRequestUri(request)
.replacePath(null)
.build()
.toUriString();
return new SomeDTO("user accessed at " + baseUrl, null, Collections.emptyList());
}
如果它在为 null 时应该有默认值,那么我更愿意在对象本身中这样做,例如:
@GetMapping(value = "/somethingEndpoint", produces = MediaType.APPLICATION_JSON_VALUE)
public SomeDTO getSomething(HttpServletRequest request) throws IOException, InterruptedException {
final String baseUrl = ServletUriComponentsBuilder.fromRequestUri(request)
.replacePath(null)
.build()
.toUriString();
return new SomeDTO("user accessed at " + baseUrl, null, Collections.emptyList())
.handleNullValues();
}
public record SomeDTO(String nameOfUser, String lastAccessedInfo, List<SomeDTO> recursiveIsFun) {
public SomeDTO handleNullValues(){
if(lastAccessedInfo == null){
lastAccessedInfo = "default value";
}
return this;
}
}
我有自定义的简单端点,returns 一些对象(在我的案例中记录)。我想验证返回的输出数据的正确性(例如,输出 DTO 确实将所有字段设置为非空值)。
执行此类验证的最佳位置在哪里? 是否可以更正验证器中的返回值(例如,将字段“上次访问资源”的值 null 更改为“尚未访问资源”)
示例说明代码:
public record SomeDTO(String nameOfUser, String lastAccessedInfo, List<SomeDTO> recursiveIsFun) {
}
@GetMapping(value = "/somethingEndpoint", produces = MediaType.APPLICATION_JSON_VALUE)
public SomeDTO getSomething(HttpServletRequest request) throws IOException, InterruptedException {
final String baseUrl = ServletUriComponentsBuilder.fromRequestUri(request)
.replacePath(null)
.build()
.toUriString();
return new SomeDTO("user accessed at " + baseUrl, null, Collections.emptyList());
}
如果它在为 null 时应该有默认值,那么我更愿意在对象本身中这样做,例如:
@GetMapping(value = "/somethingEndpoint", produces = MediaType.APPLICATION_JSON_VALUE)
public SomeDTO getSomething(HttpServletRequest request) throws IOException, InterruptedException {
final String baseUrl = ServletUriComponentsBuilder.fromRequestUri(request)
.replacePath(null)
.build()
.toUriString();
return new SomeDTO("user accessed at " + baseUrl, null, Collections.emptyList())
.handleNullValues();
}
public record SomeDTO(String nameOfUser, String lastAccessedInfo, List<SomeDTO> recursiveIsFun) {
public SomeDTO handleNullValues(){
if(lastAccessedInfo == null){
lastAccessedInfo = "default value";
}
return this;
}
}