我已经为我的bean字段验证做了自定义注释。我使用@Age(value = 10)
注释来验证年龄。我编写了如下代码。
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Documented
@Constraint(validatedBy = AgeConstraintValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Age {
String message() default "{Age is not valid }";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int value();
}
这是年龄限制验证器的代码
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class AgeConstraintValidator implements ConstraintValidator< Age, Long> {
private Age age;
@Override
public void initialize(Age age) {
this.age = age;
}
@Override
public boolean isValid(Long dob, ConstraintValidatorContext context) {
System.out.print(" age in annotion");
if(dob != age.value()){
return true;
}
return false;
}
}
现在当我在我的bean中使用@Age(value = 10)时,它不会被称为Age annotation。任何人都可以告诉我我的代码有任何错误。当我创建我的bean对象并为测试指定年龄不同但我无法在bean的字段上获得任何验证。
答案 0 :(得分:1)
Spring
不会自动获取此自定义注释。你必须通过定义BeanPostProcessor让Spring知道。创建一个实现它的类
对于e-g
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.BeansException;
public class InitHelloWorld implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BeforeInitialization : " + beanName);
return bean; // you can return any other object as well
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("AfterInitialization : " + beanName);
return bean; // you can return any other object as well
}
}
并在spring config xml中提及此bean,如下所示
<bean class="<your pack>.InitHelloWorld" />