1, why do you want to customize? Through the previous study, learned a lot of common annotations, but, there are always some demand .... 2. Case study (mobile phone number format) 2.1. Entity Beans to validate
Public class loginvo { @NotNull // custom annotations private String Mobile; @NotNull @Length (min=+) private String password; // omit Get Set Method }
2.2. Custom IsMobile Annotation Class
ImportStaticJava.lang.annotation.elementtype.annotation_type;importStaticJava.lang.annotation.elementtype.constructor;importStaticJava.lang.annotation.elementtype.field;importStaticJava.lang.annotation.elementtype.method;importStaticJava.lang.annotation.elementtype.parameter;importStaticJava.lang.annotation.retentionpolicy.runtime;import Java.lang.annotation.documented;import Java.lang.annotation.retention;import Java.lang.annotation.target;import Javax.validation.constraint;import Javax.validation.Payload; @Target ({METHOD, FIELD, Annotation_type, CONSTRUCTOR, PARAMETER}) @Retention (RUNTIME) @Documented @constraint ( Validatedby= {Ismobilevalidator.class }) Public@interface IsMobile {//Allow empty PropertiesBoolean required ()default true; //If the checksum does not pass the returned prompt informationString message ()default "cell phone number format error"; Class<?>[] Groups ()default { }; Class<? Extends payload>[] Payload ()default { };}
2.3. Calibrator
Import Javax.validation.constraintvalidator;import Javax.validation.constraintvalidatorcontext;import Org.apache.commons.lang3.stringutils;import Com.imooc.miaosha.util.ValidatorUtil; //ismobile: Custom Annotations//String: annotation parameter type Public classIsmobilevalidator implements Constraintvalidator<ismobile, string> { //The default value, _false, is used to receive custom required on annotations PrivateBoolean required =false; //1, initialization method: Through this method we can get our annotations Public voidInitialize (IsMobile constraintannotation) {//constraintannotation.required () receives our custom properties, is it emptyRequired =constraintannotation.required (); } //2. Logic processing Publicboolean isValid (String value, Constraintvalidatorcontext context) {//2.1. If the permission is empty, return the result directly if(required) {returnValidatorutil.ismobile (value); }Else { //2.2, not allowed to empty//2.2.1, verifying whether it is empty if(Stringutils.isempty (value)) {return true; }Else { returnValidatorutil.ismobile (value); } } } }
3. Summary
++ groups () + payload () must; annotation Validator class: Inheriting Constraintvalidator class < annotation class, annotation parameter type > + two methods (Initialize: Initialize operation , IsValid: Logical processing)
jsr-303 parameter Check-custom check annotations