package com.loan.modules.extbiz.in.rabbitmq.util; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Constraint(validatedBy = IsFormatValidator.class) //具体的实现 @Target( { java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.FIELD }) @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Documented public @interface IsFormat { String message() default "{org.hibernate.validator.constraints.NotEmpty.message}"; int length() ; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
package com.loan.modules.extbiz.in.rabbitmq.util; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; /** * * @description 功能描述: 自定义注解验证不能为空和长度 * @param 参 数: * @Createdate 建立日期: 2017年5月4日下午2:33:38 */ public class IsFormatValidator implements ConstraintValidator<IsFormat, Object>{ private int Valuelength; @Override public boolean isValid(Object IdNumber, ConstraintValidatorContext constraintValidatorContext) { String message=constraintValidatorContext.getDefaultConstraintMessageTemplate(); if(IdNumber==null||IdNumber.toString().equals("")){ constraintValidatorContext.disableDefaultConstraintViolation();//禁用默认的message的值 constraintValidatorContext .buildConstraintViolationWithTemplate(message+"不能为空").addConstraintViolation(); return false; } if(IdNumber.toString().length()>Valuelength){ constraintValidatorContext.disableDefaultConstraintViolation();//禁用默认的message的值 constraintValidatorContext .buildConstraintViolationWithTemplate(message+"长度不能超过"+Valuelength+"位").addConstraintViolation(); return false; } return true; } @Override public void initialize(IsFormat constraintAnnotation) { Valuelength=constraintAnnotation.length(); } }