我正在尝试使用 Spring 验证执行验证。我想知道执行主要取决于用户操作的验证的最佳做法是什么,此后,我有三种不同的方法,但我不知道哪种方法最好。
假设,我们有以下类 Foo 来验证和许多不同的验证规则,具体取决于用户执行的操作。
public class Foo {
private String name;
private int age;
private String description;
private int evaluation;
// getters, setters
}
执行这些验证的最佳方式是什么(例如:在创建期间只需要姓名和年龄,在评估操作期间,我只需要验证评估等等)
解决方案 1:每个验证规则一个验证器类
public class CreateFooValidator implements Validator {
//validation for action create
}
public class EvaluateFooValidator implements Validator {
//validation for evaluate action
}
解决方案 2:一个具有多种方法的验证器类
public class FooValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Foo.class.equals(clazz);
}
//the default validate method will be used to validate during create action
@Override
public void validate(Object target, Errors errors) {
//validation required
}
//method to validate evaluate action
public void validateFooEvaluation(Object target, Errors errors) {
//validation required
}
//other validation methods for other actions
}
解决方案 3:Foo 类中的附加属性操作,一个验证器
public class Foo {
private String name;
private int age;
private String description;
private int evaluation;
private String actionOnFoo;
// getters, setters
}
public class FooValidator implements Validator {
private final Foo foo = (Foo) target;
@Override
public boolean supports(Class<?> clazz) {
return Foo.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
//test which action is performed by user
if ("create".equals(foo.getActionOnFoo())) {
//call for private method that performs validation for create action
}
}
//all private methods
}
3 或其他解决方案中最好的解决方案是什么?谢谢!