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

上一节中我们自定义的@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. linux系统开机过程描述

    本文描述linux系统开机过程,属于个人理解范畴,如果文中表述有误请大家批评指正! 计算机开机之后,首先要加载BIOS(基本输入输出系统)信息,BIOS包含了很多重要的信息,包括CPU信息,设备启动顺 ...

  2. CentOS 6.3上搭建PPTP VPN

    系统版本:CentOS 6.3_x86_64 eth0:172.16.10.72(实验环境当公网IP使用) eth1:192.168.100.50 1.检测是否支持ppp模块 # cat /dev/p ...

  3. 数学(GCD,计数原理)HDU 5656 CA Loves GCD

    CA Loves GCD Accepts: 135 Submissions: 586 Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 2621 ...

  4. 动态规划(背包问题):POJ 1742 Coins

    Coins Time Limit: 3000MS   Memory Limit: 30000K Total Submissions: 32955   Accepted: 11199 Descripti ...

  5. 【二分】NEERC15 L Landscape Improved(2015-2016 ACM-ICPC)(Codeforces GYM 100851)

    题目链接: http://codeforces.com/gym/100851 题目大意: 一个宽度为N的网格图,i上有h[i]高的方块.现在你有W个方块,问怎么放使得最终的最高点最高. 只要一个格子的 ...

  6. 暴力求解——Equivalent Strings

    Submit Status Description Today on a lecture about strings Gerald learned a new definition of string ...

  7. bzoj 1089 [SCOI2003]严格n元树(DP+高精度)

    1089: [SCOI2003]严格n元树 Time Limit: 1 Sec  Memory Limit: 162 MBSubmit: 1250  Solved: 621[Submit][Statu ...

  8. 搜索——[HAOI2012]添加号

    题目:[HAOI2012]添加号 描述: [题目描述] 有一个由数字1,2,…9组成的数字串(长度不超过8),问如何将M(M<=5)个加号"+"插入到这个数字串中,使所形成的 ...

  9. 使用 HTMLTestRunner.py

    HTMLTestRunner.py python 2版本 下载地址:http://tungwaiyip.info/software/HTMLTestRunner.html 教程:http://www. ...

  10. 记录下mybatis中#{}和${}传参的区别

    最近在用mybatis,之前用过ibatis,总体来说差不多,不过还是遇到了不少问题,再次记录下, 比如说用#{},和 ${}传参的区别, 使用#传入参数是,sql语句解析是会加上"&quo ...