我试图获得与在控制器的对象参数中使用 @Valid 时相同的结果。当对象无效时,我的具有@RestControllerAdvice 的 ExceptionHandlerController 会抛出异常 (MethodArgumentNotValidException)。
在我的情况下,我想验证一个对象,但我只能在服务层验证它。该对象具有 bean 验证注释,因此我尝试以编程方式为我的 ExceptionHandlerController 处理它抛出 MethodArgumentNotValidException,但我没有成功。
到目前为止,我有这个:
private void verifyCard(CardRequest card) {
BeanPropertyBindingResult result = new BeanPropertyBindingResult(card, "card");
SpringValidatorAdapter adapter = new SpringValidatorAdapter(this.validator);
adapter.validate(card, result);
if (result.hasErrors()) {
try {
throw new MethodArgumentNotValidException(null, result);
} catch (MethodArgumentNotValidException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
第一个参数来自 MethodParameter 类型,我无法创建此对象。这是处理我的问题的最佳方法吗?
编辑 1:
我无法删除 try/catch 块。当我删除它时,我收到编译错误。如何解决?
我试图在 Kotlin 的静态字段中注入一个值,但我没有成功。
我知道一个 Java 的解决方法,那么在 Kotlin 中,这个 Java 代码的等价物是什么?
@Component
public class GlobalValue {
public static String DATABASE;
@Value("${mongodb.db}")
public void setDatabase(String db) {
DATABASE = db;
}
}
Run Code Online (Sandbox Code Playgroud)