约束条件组合--把多个约束组合成一个约束

上一节中我们自定义的@CheckCase是用来检查是否String为大写的注释,默认情况下当我们的String为null的时候也被认为正确的

CaseMode枚举

package test02;

public enum CaseMode {
UPPER,
LOWER;
}

User类

package test02;

public class User {
@CheckCase(value=CaseMode.UPPER)
private String name; // @CheckCase(CaseMode.UPPER)
// private String email="email";
}

@CheckCase

package test02;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
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 })
@Retention(RUNTIME)
@Constraint(validatedBy = CheckCaseValidator.class)
@Documented
public @interface CheckCase {
String message() default "{test02.CheckCase.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
CaseMode value(); }

验证器

package test02;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext; public class CheckCaseValidator implements ConstraintValidator<CheckCase, String> {
private CaseMode caseMode; public void initialize(CheckCase constraintAnnotation) {
this.caseMode = constraintAnnotation.value();
} public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
if (object == null)
return true;
boolean isValid;
if (caseMode == CaseMode.UPPER) {
isValid = object.equals(object.toUpperCase());
} else {
isValid = object.equals(object.toLowerCase());
}
// if(!isValid) {
// constraintContext.disableDefaultConstraintViolation();
// constraintContext.buildConstraintViolationWithTemplate( "{com.mycompany.constraints.CheckCase.message}" ).addConstraintViolation();
// }
return isValid;
}
}

运行结果:

@Test
public void test01(){
User u=new User();
Set<ConstraintViolation<User>> validate = validator.validate(u);
System.out.println(validate.size());
//
System.out.println(validate);
//[]
}

所以这一节我们将该注释和@notNull的注释组合起来

一,创建一个约束条件组合 @UpperNotNull

package test03;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target; import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.constraints.NotNull; import test02.CheckCase;
import test02.CaseMode; @NotNull
@CheckCase(CaseMode.UPPER)
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = {})
@Documented
public @interface UpperNotNull {
String message() default "{com.mycompany.constraints.validlicenseplate}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {}; }
package test02;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
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 })
@Retention(RUNTIME)
@Constraint(validatedBy = CheckCaseValidator.class)
@Documented
public @interface CheckCase {
String message() default "{test02.CheckCase.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
CaseMode value(); }

属性文件中的内容

test02.CheckCase.message = must be false {value}
com.mycompany.constraints.validlicenseplate=must not be null and must be Upper writen

二,创建Po测试类

package test03;

public class User {
@UpperNotNull
private String name; // @CheckCase(CaseMode.UPPER)
// private String email="email";
}

三,测试

package test03;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.junit.BeforeClass;
import org.junit.Test;
public class MyTest { private static Validator validator; /**
* 获取一个验证器
*/
@BeforeClass
public static void setUp() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void test01(){
User u=new User();
Set<ConstraintViolation<User>> validate = validator.validate(u);
System.out.println(validate.size());
//
System.out.println(validate);
//[ConstraintViolationImpl{interpolatedMessage='不能为null', propertyPath=name, rootBeanClass=class test03.User, messageTemplate='{javax.validation.constraints.NotNull.message}'}]
} }

当我们把Po类中的name改成:

package test03;

public class User {
@UpperNotNull
private String name="wangyang"; // @CheckCase(CaseMode.UPPER)
// private String email="email";
}

再测试:

@Test
public void test01(){
User u=new User();
Set<ConstraintViolation<User>> validate = validator.validate(u);
System.out.println(validate.size());
//
System.out.println(validate);
//[ConstraintViolationImpl{interpolatedMessage='must be false UPPER', propertyPath=name, rootBeanClass=class test03.User, messageTemplate='{test02.CheckCase.message}'}]
}

hibernate_validator_10的更多相关文章

随机推荐

  1. GPIO模拟串口注意是事项

    GPIO模拟串口需要注意的事项如下:(程序见我的博客第一篇) 1.由于串口是异步通信,则串口发送必须满足宽度要求. (1)假设串口的波特率是9600bps(1s传输9600个bit),则传输1bit需 ...

  2. 【HDOJ】2896 病毒侵袭

    AC自动机模板题. #include <iostream> #include <cstdio> #include <cstring> #include <qu ...

  3. Wine install, 卸载的方法

    EL6 (RHEL6 and SL6) Required packages for proper building of 32-bit Wine on 64-bit EL6 yum install - ...

  4. Expanding Rods(二分)

    Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 10287   Accepted: 2615 Description When ...

  5. poj 1273 Drainage Ditches (网络流 最大流)

    网络流模板题. ============================================================================================ ...

  6. 2015第37周一struts2 jstl 标签

    1.在jstl中使用struts2  <c:forEach var="ee" items="${requestScope.serviceList}" &g ...

  7. 数学概念——A 几何概型

    You are going from Dhaka to Chittagong by train and you came to know one of your old friends is goin ...

  8. 什么是Socket,为什么要用Socket

    应用层通过传输层进行数据通信时,TCP和UDP会遇到同时为多个应用程序进程提供并发服务的问题.多个TCP连接或多个应用程序进程可能需要通过同一个TCP协议端口传输数据.为了区别不同的应用程序进程和连接 ...

  9. 男人的网站—Indochino不完全解析 | 曾亮.ME

    男人的网站-Indochino不完全解析 | 曾亮.ME 亮兄 可以参考一下国内的 ROMWE SHEINSIDE

  10. M - 昂贵的聘礼 - poj1062

    Description 年轻的探险家来到了一个印第安部落里.在那里他和酋长的女儿相爱了,于是便向酋长去求亲.酋长要他用10000个金币作为聘礼才答应把女儿嫁给他.探险家拿不出这么多金币,便请求酋长降低 ...