Spring 为 bean 验证提供了三个句柄。
1.抽象类AbstractPropertyValidationAnnotationHandler
2.抽象类AbstractMethodValidationAnnotationHandler
3.抽象类ClassValidationAnnotationHandler
在这个例子中,我正在实现自定义注释 CustomAnnotationHandle
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
Class CustomAnnotationHandle extends Annotation{
public abstract String value();
}
要实现属性验证的自定义注释,我们需要扩展 AbstractPropertyValidationAnnotationHandler 类。
AbstractPropertyValidationAnnotationHandler 提供 createValidationRule 抽象方法
protected abstract AbstractValidationRule createValidationRule(Annotation annotation, Class class1, String s);
所以,扩展类必须提供实现
protected abstract AbstractValidationRule createValidationRule(Annotation annotation, Class class1, String s)
public class CustomPropertyAnnotationHandler extends AbstractPropertyValidationAnnotationHandler
{
public CustomPropertyAnnotationHandler()
{
super(new Class[] {
XXX.XXX.PackageLevle.CustomAnnotationHandle // as it takes array of custom annotation ,so we can pass more than one
// overwriting abstract method
protected AbstractValidationRule createValidationRule(Annotation annotation, Class class1, String s){
CustomAnnotationHandle value = (CustomAnnotationHandle)annotation;
return TestValidationRule(value.getValue());
// as you can see it return AbstractValidationRule.So, we need a class to give our bean specific validation rule.In our case it is
//TestValidationRule
}
}
}
public class TestValidationRule extends AbstractValidationRule
{
public TestValidationRule (String valuetest)
{
super();
this.valuetest = valuetest;
}
Private String valuetest;
}
Spring 提供了 AnnotationBeanValidationConfigurationLoader 类,该类用于spring自带的注解,用于bean的校验。
DefaultValidationAnnotationHandlerRegistry 类用作 defaultHandlerRegistry。但是如果我们需要提供自己的注解,那么我们
需要扩展 AnnotationBeanValidationConfigurationLoader 并通过方法设置我们具体的handleregistry
setHandlerRegistry(new CustomPropertyAnnotationHandler());
Class DefaultValidationAnnotationHandlerRegistry用于注册spring自己的注解进行bean验证。它通过注册bean
调用SimpleValidationAnnotationHandlerRegistry类的registerPropertyHandler方法。所以对于我们的自定义注解我们需要
调用SimpleValidationAnnotationHandlerRegistry类的registerPropertyHandler方法注册CustomPropertyAnnotationHandler
public class OurBeanSpecificValidationLoader extends AnnotationBeanValidationConfigurationLoader
{
public OurBeanSpecificValidationLoader ()
{
super();
setHandlerRegistry(new OurSpecificAnnotationHandleRegistery ());
}
}
public class OurSpecificAnnotationHandleRegistery extends DefaultValidationAnnotationHandlerRegistry
{
public OurSpecificAnnotationHandleRegistery ()
{
registerPropertyHandler(new CustomPropertyAnnotationHandler() );
}
}
这样你就有了 bean valiation.E.g 的自定义注释
@CustomAnnotationHandle(value = "test")
private Object test;