0

AnnotationConfigApplicationContext创建了带@Configuration注释的类作为参数:

@Configuration
class Config {

    @Bean
    public LocalValidatorFactoryBean localValidatorFactoryBean() {
        return new LocalValidatorFactoryBean();
    }

    @Bean
    public A aBean() {
        return new A();
    }

    @Bean
    public B aBean() {
        return new B();
    }
}

地点A和地点B

class A {

    @Min(1)
    public int myInt;
}

class B {

    @Autowire(required = true)
    @Valid
    public A aBean;
}

Q:这种情况下是否可以让Spring来处理@Valid注解?

PS:目前我有以下工作实施B

class B {

    public A aBean;

    public void setABean(A aBean, Validator validator) {
        if (validator.validate(aBean).size() > 0) {
            throw new ValidationException();
        }
        this.aBean = aBean;
    }
}

这个 impl 对我来说似乎有点笨拙,我想替换它。请帮忙 :)

4

1 回答 1

1

看起来您想在注入过程中验证您的 bean。你可以 在这里阅读。

这是一个例子:

public class BeanValidator implements org.springframework.validation.Validator, InitializingBean {

private Validator validator;

public void afterPropertiesSet() throws Exception {
    ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
    validator = validatorFactory.usingContext().getValidator();
}

public boolean supports(Class clazz) {
    return true;
}

public void validate(Object target, Errors errors) {
    Set<ConstraintViolation<Object>> constraintViolations = validator.validate(target);
    for (ConstraintViolation<Object> constraintViolation : constraintViolations) {
        String propertyPath = constraintViolation.getPropertyPath().toString();
        String message = constraintViolation.getMessage();
        errors.rejectValue(propertyPath, "", message);
    }
}

}

您将需要实现 InitializingBean,以便能够在设置 bean 后对其进行验证。

于 2012-07-30T08:30:00.973 回答