验证Bean内的Bean

时间:2013-05-12 23:50:44

标签: java spring

我有以下豆子

public class MyModel {
  @NotNull
  @NotEmpty
  private String name;

  @NotNull
  @NotEmpty
  private int age;

  //how do you validate this?
  private MySubModel subModel;
}

public class MySubModel{

  private String subName;

}

然后我使用@Valid注释从控制器端验证这一点。

谢谢

2 个答案:

答案 0 :(得分:3)

您可以使用Bean Validation(JSR-303)定义自己的自定义验证,例如,这里是简单的自定义邮政编码验证,通过使用您可以轻松验证的自定义注释进行注释:

@Documented
@Constraint(validatedBy = ZipCodeValidator.class)
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ZipCode {
    String message() default "zip code must be five numeric characters";

    Class<?>[] groups() default {};

    Class<?>[] payload() default {};
}

自定义验证类,您可以使用自定义bean,例如<YourAnnotationClassName,TypeWhichIsBeingValidated>

public class ZipCodeValidator implements ConstraintValidator<ZipCode, String> {

    @Override
    public void initialize(ZipCode zipCode) {
    }

    @Override
    public boolean isValid(String string, ConstraintValidatorContext context) {
        if (string.length() != 5)
            return false;
        for (char c : string.toCharArray()) {
            if (!Character.isDigit(c))
                return false;
        }
        return true;
    }

}

以下是它的用法:

public class Address{

  @ZipCode
  private String zip;

}

答案 1 :(得分:2)

你可以试试这个:

public class MyModel {

    @NotNull
    @NotEmpty
    private String name;

    @NotNull
    @NotEmpty
    private int age;

    // how do you validate this?
    private MySubModel subModel;

    @NotNull
    @Size(min=5, max=10)
    public String getSubModelSubName() {
        return subModel == null ? null : subModel.getSubName();
    }
}

另一种可能性是在内部bean中使用@Valid注释。例如:

public class MySubModel{

  @NotNull
  @Size(min=5, max=10)
  private String subName;

}

然后,你必须像这样编写你的主类:

public class MyModel {

    @NotNull
    @NotEmpty
    private String name;

    @NotNull
    @NotEmpty
    private int age;

    // how do you validate this?
    @Valid
    private MySubModel subModel;

}

我使用的是Spring Boot 1.2.5