Spring @Valid、@NotEmpty、@NotBlank...校验参数,(属性、内部对象、内部类)

一:pom依赖

  
	javax.validation  
	validation-api  
	1.1.0.Final  
  
  
	org.hibernate  
	hibernate-validator  
	5.2.1.Final  

二:自定义校验工具类

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

public class ValidateUtil {
	private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	public static  void validate(T t) {
		Validator validator = factory.getValidator();
		Set> constraintViolations = validator.validate(t);
		for (ConstraintViolation constraintViolation : constraintViolations) {
			throw new RuntimeException(constraintViolation.getMessage());
		}
	}
}

三:dubbo接口入参实体类

import java.io.Serializable;
import java.util.List;
import javax.validation.Valid;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Setter
@Getter
@ToString
public class IolAdvanceQuery implements Serializable{
	private static final long serialVersionUID = 3663628633261839802L;
	
	@NotEmpty(message = "销售方公司编码不能为空")
	@Size(min = 1, max = 10, message = "销售方公司编码长度应在1-10之间")
	@Pattern(regexp = "[A-Za-z0-9]*", message = "销售方公司编码只能是英文、数字")
	@ApiModelProperty("销售方公司编码")
	private String companyCode;
	
	@Valid // 让subs的属性也参与校验  【外部类】
	@NotEmpty(message = "子客户不能为空")
	private List subs;
	
	@Valid // 让subReqs的属性也参与校验   【内部类】
	@NotEmpty(message = "子客户Req不能为空")
	private SubIolAdvanceReq subReqs;
	
	@Getter
    @Setter
    @ToString
	public static class SubIolAdvanceReq implements Serializable {
		private static final long serialVersionUID = -4603105521668086927L;
		@NotEmpty(message = "子销售方Req公司编码不能为空...")
		@ApiModelProperty("子销售方Req公司编码")
		private String companyCode;
	}
}

依赖的外部类

import java.io.Serializable;
import org.hibernate.validator.constraints.NotEmpty;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Setter
@Getter
@ToString
public class SubIolAdvanceQuery implements Serializable {
	private static final long serialVersionUID = 270888484388171346L;
	@ApiModelProperty("子客户编码")
	@NotEmpty(message = "子客户编码不能为空")
	private String customerCode;
}

三:服务调用示例

public Result> getInvoiceOnlineList(IolAdvanceQuery query) {
    	ValidateUtil.validate(query); // 入参校验 可根据不同业务需求自由选择,抛出异常、捕获异常;或者自定义返回 校验结果,判断是否校验通过,返回提示信息;本列是采用 抛出异常的 方式。
    ....
}

 

你可能感兴趣的:(Spring @Valid、@NotEmpty、@NotBlank...校验参数,(属性、内部对象、内部类))