gpt4 book ai didi

java - Bean 验证不适用于 spring webflux

转载 作者:行者123 更新时间:2023-12-04 13:43:09 33 4
gpt4 key购买 nike

我已经重构了我的代码以使用 spring webflux 但现在 @Valid停止工作。
它没有验证请求正文。

@PostMapping(value = "/getContactInfo",produces = "application/json",consumes = "application/json")
public Flux<UserContactsModel> getUserContacts(@Valid @RequestBody Mono<LoginModel> loginDetail) {

loginDetail.log();
return contactInfoService
.getUserContacts(loginDetailApiMapper.loginModelMonoToLoginBoMono(loginDetail))
.flatMapIterable(
userContactsBO -> contactInfoMapper.userContactBoToModelList(userContactsBO));
}

我得到 200 OK 代替了我从 Controller 建议中返回的错误请求。

编辑 1:
   import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

public class LoginModel implements Serializable {

private String clientId;

@Pattern(regexp = "^[a-zA-Z0-9]*$", message = "Login ID is invalid")
@NotNull
private String loginId;
}

更新 1:
像这样更改代码并在类级别添加@Validated
@RestController
@Validated
public class ContactInfoController implements ContactInfoApi {
public Flux<UserContactsModel> getUserContacts(@RequestBody Mono<@Valid LoginModel> loginDetail) {

我收到 javax.validation.ConstraintDeclarationException: HV000197: No value extractor found for type parameter 'T' of type reactor.core.publisher.Mono。

最佳答案

没有什么对我有用。所以我使用 javax.validator 手动验证了它。

@Autowired private Validator validator;

public Flux<UserContactsModel> getUserContacts(@RequestBody Mono<@Valid LoginModel> loginDetail) {

return loginDetail
.filter(this::validate)
.map(....);
}

private boolean validate(LoginModel loginModel) {

Set<ConstraintViolation<LoginModel>> constraintViolations = validator.validate(loginModel);

if (CollectionUtils.isNotEmpty(constraintViolations)) {
StringJoiner stringJoiner = new StringJoiner(" ");
constraintViolations.forEach(
loginModelConstraintViolation ->
stringJoiner
.add(loginModelConstraintViolation.getPropertyPath().toString())
.add(":")
.add(loginModelConstraintViolation.getMessage()));
throw new RuntimeException(stringJoiner.toString());
}

return true;
}

关于java - Bean 验证不适用于 spring webflux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53887930/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com