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

上一节中我们自定义的@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. 【HDOJ】2822 Dogs

    bfs. /* 2822 */ #include <iostream> #include <cstdio> #include <cstring> #include ...

  2. 【贪心】Vijos P1615 旅行

    题目链接: https://vijos.org/p/1615 题目大意: N条路,路的高度给你,走一条路的耗费体力是从上一条路的高度到当前路高度的绝对值差. 可以改变一条路的高度,耗费的体力等于改变前 ...

  3. Json.Net学习笔记(十) 保持对象引用

    更多内容见这里:http://www.cnblogs.com/wuyifu/archive/2013/09/03/3299784.html 默认情况下,Json.Net将通过对象的值来序列化它遇到的所 ...

  4. codevs2492 上帝造题的七分钟 2

    2492 上帝造题的七分钟 2 题目描述 Description XLk觉得<上帝造题的七分钟>不太过瘾,于是有了第二部. "第一分钟,X说,要有数列,于是便给定了一个正整数数列 ...

  5. 控制uwsgi 的信号量

    最近在用nginx+uwsgi+djano搭建一个网站,当.py文件修改后,如果不重启uwsgi,修改无法应用. 查了下uwsgi的相关文档 ,找到几个解决方案.顺便翻译下以备查看 启动服务 Star ...

  6. 【行业干货】ASOS:外来快时尚品牌的入华战 - 行业干货 - 京东内部论坛 - Powered by Discuz!

    [行业干货]ASOS:外来快时尚品牌的入华战 - 行业干货 - 京东内部论坛 - Powered by Discuz! [行业干货]ASOS:外来快时尚品牌的入华战

  7. 金牌分析师助力 鲁泰A图谋再造一个“鲁泰”?_财经_中国网

    金牌分析师助力 鲁泰A图谋再造一个"鲁泰"?_财经_中国网 金牌分析师助力 鲁泰A图谋再造一个"鲁泰"?

  8. E - Find The Multiple

    题目大意 找倍数 给你一个数,找到一个能数是它的倍数的数,当然这个数只能由0和1组成.......这个数最大200,比较唬人,其实这个数在最大也不超过2^64.....简单广搜一下 ///////// ...

  9. 用Myeclipse 编写struts.xml时,自动提示

    之所以不自动提示,是因为这个xml它不知道自己的xml格式是什么有哪些标签,所以不知道该怎么提示 所以就要给它引入格式,所以要引入XSD或者DTD文件 1.首先打开MyEclipse的窗口,选择“Wi ...

  10. sql server 常用小知识点

    1. sql server的语法:中文要加 N select * from eVA_EMPBoard where name = N'施纪平' 而oracle的不用 2.