Commit 3d78076d by huangfusuper

参数校验引擎项目初始化

parents
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.byit</groupId>
<artifactId>byit-validation-satrter</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<!--自动配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.byit.adaptation;
import org.apache.commons.lang3.StringUtils;
import java.util.regex.Pattern;
/**
* 规则校验适配器
* @author huangfu
*/
public class ValidationAdaptation {
/**
* 中国电信号码格式验证 手机段: 133,149,153,173,177,180,181,189,199,1349,1410,1700,1701,1702
**/
private static final String CHINA_TELECOM_PATTERN = "(?:^(?:\\+86)?1(?:33|49|53|7[37]|8[019]|99)\\d{8}$)|(?:^(?:\\+86)?1349\\d{7}$)|(?:^(?:\\+86)?1410\\d{7}$)|(?:^(?:\\+86)?170[0-2]\\d{7}$)";
/**
* 中国联通号码格式验证 手机段:130,131,132,145,146,155,156,166,171,175,176,185,186,1704,1707,1708,1709
**/
private static final String CHINA_UNICOM_PATTERN = "(?:^(?:\\+86)?1(?:3[0-2]|4[56]|5[56]|66|7[156]|8[56])\\d{8}$)|(?:^(?:\\+86)?170[47-9]\\d{7}$)";
/**
* 中国移动号码格式验证
* 手机段:134,135,136,137,138,139,147,148,150,151,152,157,158,159,178,182,183,184,187,188,198,1440,1703,1705,1706
**/
private static final String CHINA_MOBILE_PATTERN = "(?:^(?:\\+86)?1(?:3[4-9]|4[78]|5[0-27-9]|78|8[2-478]|98)\\d{8}$)|(?:^(?:\\+86)?1440\\d{7}$)|(?:^(?:\\+86)?170[356]\\d{7}$)";
/**
* 邮箱验证
*/
private static final String EMAIL_PATTERN = "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?";
/**
* @NotNull 校验 非空校验
* @param value
* @return
*/
public static boolean dataNotNull(Object value){
return value != null;
}
/**
* NotBank校验
* @param value
* @return
*/
public static boolean dataNotBank(String value){
return StringUtils.isNotBlank(value);
}
/**
* 长度校验 校验长度是否满足规定值
* @param value 数值
* @param length 标准长度
* @return
*/
public static boolean lengthValidation(String value,int length){
if(dataNotNull(value)){
return value.length() == length;
}
return false;
}
/**
* 长度校验 校验字符串长度是否小于规定值
* @param value
* @param minLength 最小长度
* @return
*/
public static boolean minLengthValidation(String value,int minLength){
if(dataNotNull(value)){
return value.length() >= minLength;
}
return false;
}
/**
* 长度校验 校验字符串长度是否小于规定值
* @param value
* @param maxLength 最小长度
* @return
*/
public static boolean maxLengthValidation(String value,int maxLength){
if(dataNotNull(value)){
return value.length() <= maxLength;
}
return false;
}
/**
* 长度校验 校验字符串是否在某一区间内 0>=100>=101
* @param value
* @param minLength
* @param maxLength
* @return
*/
public static boolean intervalLengthValidation(String value,int minLength,int maxLength){
return minLengthValidation(value,minLength) && maxLengthValidation(value,maxLength);
}
/**
* 中国大陆手机号码校验
*
* @param phone
*
* @return
*/
public static boolean checkPhone(String phone) {
if (StringUtils.isNotBlank(phone)) {
return checkChinaMobile(phone) || checkChinaUnicom(phone) || checkChinaTelecom(phone);
}
return false;
}
/**
* 中国移动手机号码校验
*
* @param phone
*
* @return
*/
public static boolean checkChinaMobile(String phone) {
if (StringUtils.isNotBlank(phone)) {
Pattern regexp = Pattern.compile(CHINA_MOBILE_PATTERN);
return regexp.matcher(phone).matches();
}
return false;
}
/**
* 中国联通手机号码校验
*
* @param phone
*
* @return
*/
public static boolean checkChinaUnicom(String phone) {
if (StringUtils.isNotBlank(phone)) {
Pattern regexp = Pattern.compile(CHINA_UNICOM_PATTERN);
return regexp.matcher(phone).matches();
}
return false;
}
/**
* 中国电信手机号码校验
*
* @param phone 手机号码
*
* @return boolean
*/
public static boolean checkChinaTelecom(String phone) {
if (StringUtils.isNotBlank(phone)) {
Pattern regexp = Pattern.compile(CHINA_TELECOM_PATTERN);
return regexp.matcher(phone).matches();
}
return false;
}
/**
* 邮箱验证
* @param email
* @return
*/
public static boolean emailValidation(String email){
if (StringUtils.isNotBlank(email)) {
Pattern regexp = Pattern.compile(EMAIL_PATTERN);
return regexp.matcher(email).matches();
}
return false;
}
/**
* 隐藏手机号中间四位
*
* @param phone
*
* @return java.lang.String
*/
public static String hideMiddleMobile(String phone) {
if (StringUtils.isNotBlank(phone)) {
phone = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
}
return phone;
}
}
package com.byit.annotation;
import java.lang.annotation.*;
/**
* 他是一个标记注解,仅用于拦截器拦截使用
* 注解范围是方法上
* 定义在方法上,证明此方法需要被拦截器拦截,需要其中参数被校验
* @author huangfu
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DataValidation {}
package com.byit.annotation;
import com.byit.selector.interfaces.ValidationSelector;
import java.lang.annotation.*;
/**
* 元注解 标记此注解为校验选择的注解,同时此注解需要实现自定义的校验类
* @author huangfu
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface MetaAnnotation {
/**
* 定义注解类所指定的实现类
* @return
*/
Class<? extends ValidationSelector> validationClass();
}
package com.byit.annotation;
import java.lang.annotation.*;
/**
* 这个注解是一个标记注解,他的作用是为了标记此参数内部有属性是需要进行参数验证的
* @author huangfu
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface ParamValidation {
}
package com.byit.annotation.annotationselector;
import com.byit.annotation.MetaAnnotation;
import com.byit.selector.EmailValidationSelector;
import com.byit.selector.LengthValidationSelector;
import java.lang.annotation.*;
/**
* 邮箱验证
* @author huangfu
*/
@Target({ElementType.PARAMETER,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@MetaAnnotation(validationClass = EmailValidationSelector.class)
public @interface EmailValidation {
/**
* 错误信息
* @return
*/
String errorMessage() default "邮箱格式不正确";
}
package com.byit.annotation.annotationselector;
import com.byit.annotation.MetaAnnotation;
import com.byit.selector.LengthValidationSelector;
import java.lang.annotation.*;
/**
* 长度校验
* @author huangfu
*/
@Target({ElementType.PARAMETER,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@MetaAnnotation(validationClass = LengthValidationSelector.class)
public @interface LengthValidation {
/**
* 错误信息
* @return
*/
String errorMessage() default "{com.byit.annotation.annotationselector.LengthValidation#errorMessage}";
/**
* 定长字符串
* @return
*/
int strLength() default -1;
/**
* 最小长度
* @return
*/
int minLength() default -1;
/**
* 最大长度
* @return
*/
int maxLength() default -1;
}
package com.byit.annotation.annotationselector;
import com.byit.annotation.MetaAnnotation;
import com.byit.selector.MobileNumberVerificationSelector;
import com.byit.selector.NotBankSelector;
import java.lang.annotation.*;
/**
* 手机号验证注解
* @author huangfu
*/
@Target({ElementType.PARAMETER,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@MetaAnnotation(validationClass = MobileNumberVerificationSelector.class)
public @interface MobileNumberVerification {
/**
* 错误信息
* @return
*/
String errorMessage() default "手机号码不正确";
}
package com.byit.annotation.annotationselector;
import com.byit.annotation.MetaAnnotation;
import com.byit.selector.NotBankSelector;
import java.lang.annotation.*;
@Target({ElementType.PARAMETER,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@MetaAnnotation(validationClass = NotBankSelector.class)
public @interface NotBank {
/**
* 错误信息
* @return
*/
String errorMessage() default "此值不能为null或者\"\"";
}
package com.byit.annotation.annotationselector;
import com.byit.annotation.MetaAnnotation;
import com.byit.selector.NotNullSelector;
import java.lang.annotation.*;
/**
* 非空校验
* @author huangfu
*/
@Target({ElementType.PARAMETER,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@MetaAnnotation(validationClass = NotNullSelector.class)
public @interface NotNull {
/**
* 错误信息
* @return
*/
String errorMessage() default "此值不能为null";
}
package com.byit.annotation.annotationselector;
import com.byit.annotation.MetaAnnotation;
import com.byit.selector.EmailValidationSelector;
import com.byit.selector.RegularValidationSelector;
import java.lang.annotation.*;
/**
* 判断是否符合指定的正则表达式
* @author huangfu
*/
@Target({ElementType.PARAMETER,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@MetaAnnotation(validationClass = RegularValidationSelector.class)
public @interface RegularValidation {
/**
* 错误信息
* @return
*/
String errorMessage() default "与指定的正则表达式不匹配";
/**
* 正则表达式
* @return
*/
String regularStr();
}
package com.byit.aspect;
import com.byit.annotation.MetaAnnotation;
import com.byit.annotation.ParamValidation;
import com.byit.annotation.annotationselector.NotNull;
import com.byit.exception.DataValidationException;
import com.byit.validation.Validation;
import com.byit.validation.impl.NotParamValidationImpl;
import com.byit.validation.impl.ParamValidationImpl;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
/**
* @author huangfu
*/
@Aspect
public class CheckerAspect {
private static final Logger log = LoggerFactory.getLogger(CheckerAspect.class);
private final Validation notParamValidation;
private final Validation paramValidation;
public CheckerAspect(Validation notParamValidation, Validation paramValidation) {
this.notParamValidation = notParamValidation;
this.paramValidation = paramValidation;
}
@Around("@annotation(com.byit.annotation.DataValidation)")
public Object dataValidation(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("------------------进入拦截器拦截------------------");
//获取方法参数
Object[] args = joinPoint.getArgs();
//获取方法签名
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
//参数注解,1维是参数,2维是注解
Annotation[][] annotations = method.getParameterAnnotations();
for (int i = 0; i < annotations.length; i++) {
//获取对应的参数
Object param = args[i];
//获取参数对应的注解
Annotation[] paramAnn = annotations[i];
//注解为空,直接下一个参数
if(paramAnn.length == 0){
continue;
}
/**
* 如果参数为null
* 这里存在三种情况:
* 1:此参数前存在非空校验注解
* 2:此参数有注解,但是没有校验注解
* 3:有校验注解,但是没有非空校验注解直接抛出异常
*/
if(param == null){
//是否存在非空注解
String existNotNullAnnotation = isExistNotNullAnnotation(paramAnn);
if(existNotNullAnnotation != null){
throw new DataValidationException(existNotNullAnnotation);
}if(notExistValidationAnn(paramAnn)){
//还有一种情况 参数有注解,但是不是校验注解
continue;
} else{
throw new DataValidationException("---------------第"+i+"个参数为null,无法执行校验规则---------------------");
}
}
/**
* 获取参数前的注解
* 此时有两种情况
* 1:直接校验参数规则
* 此种规则的判断方式,只需判断参数前的注解是否存在MetaAnnotation自定义元注解即可
* 2:需要对其内部属性进行校验
* 此种规则的判断方式,只需要判断前方是否存在ParamValidation注解
*/
for (Annotation annotation : paramAnn) {
//这里判断当前注解是否为ParamValidation.class
boolean isPresenceParamValidationAnnotation = annotation.annotationType().equals(ParamValidation.class);
if(isPresenceParamValidationAnnotation){
//ParamValidationImpl paramValidationImpl = new ParamValidationImpl();
paramValidation.isValidation(param);
continue;
}
//这里判断当前的注解是否可以值接通注解进行校验
boolean annotationPresent = annotation.annotationType().isAnnotationPresent(MetaAnnotation.class);
//如果存在
if(annotationPresent){
//NotParamValidationImpl notParamValidation = new NotParamValidationImpl();
notParamValidation.isValidation(annotation,param);
continue;
}
}
}
return joinPoint.proceed(args);
}
/**
* 查看是否存在非空校验注解
* @param annotations
* @return
*/
private String isExistNotNullAnnotation(Annotation[] annotations){
String message = null;
for (int i = 0; i < annotations.length; i++) {
//查看是否存在非空校验注解
boolean flag = annotations[i].annotationType().equals(NotNull.class);
if (flag){
//获取注解内部的错误提示信息
NotNull nulls = (NotNull) annotations[i];
message = nulls.errorMessage();
}
}
return message;
}
/**
* 查看是否存在校验注解
* @param annotations
* @return
*/
private boolean notExistValidationAnn(Annotation[] annotations){
//查看是否存在校验注解
for (int i = 0; i < annotations.length; i++) {
boolean equals = annotations[i].annotationType().equals(ParamValidation.class);
boolean annotationPresent = annotations[i].annotationType().isAnnotationPresent(MetaAnnotation.class);
//存在校验规则
if(equals || annotationPresent){
return false;
}
}
return true;
}
}
package com.byit.config;
import com.byit.aspect.CheckerAspect;
import com.byit.properties.ValidationProperties;
import com.byit.utils.SpringUtil;
import com.byit.validation.Validation;
import com.byit.validation.impl.NotParamValidationImpl;
import com.byit.validation.impl.ParamValidationImpl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author huangfu
*/
@Configuration
@EnableConfigurationProperties(ValidationProperties.class)
public class ValidationAuthConfigure {
/**
* 无注解 @ParamValidation 配置
* @return 返回NotParamValidationImpl对象
*/
@Bean
public Validation getNotParamValidation(){
return new NotParamValidationImpl();
}
/**
* 有注解 @ParamValidation 配置
* @return
*/
@Bean
public Validation getParamValidation(){
return new ParamValidationImpl();
}
/**
* 注册切面
* @return
*/
@Bean
public CheckerAspect getCheckerAspect(){
return new CheckerAspect(getNotParamValidation(),getParamValidation());
}
@Bean
public SpringUtil springUtil(){
return new SpringUtil();
}
}
package com.byit.exception;
/**
* 自定义异常 用于抛出参数校验失败的异常
* @author huangfu
*/
public class DataValidationException extends RuntimeException {
public DataValidationException(String message) {
super(message);
}
}
package com.byit.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 校验配置类
* @author huangfu
*/
@ConfigurationProperties("byit.validation")
public class ValidationProperties {
private boolean enabled = false;
private String url;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public ValidationProperties(boolean enabled, String url) {
this.enabled = enabled;
this.url = url;
}
public ValidationProperties() {
}
}
package com.byit.selector;
import com.byit.annotation.annotationselector.EmailValidation;
import com.byit.exception.DataValidationException;
import com.byit.properties.ValidationProperties;
import com.byit.selector.interfaces.ValidationSelector;
import com.byit.utils.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.byit.adaptation.ValidationAdaptation.emailValidation;
/**
* 邮箱格式校验
* @author huangfu
*/
public class EmailValidationSelector implements ValidationSelector<EmailValidation> {
private static final Logger log = LoggerFactory.getLogger(EmailValidationSelector.class);
@Override
public void init(EmailValidation annotation, Object value) {
log.info("---------------------------@EmailValidation 初始化-------------------------");
}
@Override
public boolean isValid(EmailValidation annotation, Object value) {
if(value instanceof String){
return emailValidation((String)value);
}
//不是字符串
throw new DataValidationException(value+"不是字符串");
}
}
package com.byit.selector;
import com.byit.annotation.annotationselector.LengthValidation;
import com.byit.exception.DataValidationException;
import com.byit.selector.interfaces.ValidationSelector;
import com.byit.adaptation.ValidationAdaptation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 长度校验
*
* @author huangfu
*/
public class LengthValidationSelector implements ValidationSelector<LengthValidation> {
private static final Logger log = LoggerFactory.getLogger(LengthValidationSelector.class);
@Override
public void init(LengthValidation annotation, Object value) {
log.info("---------------------------@LengthValidation初始化----------------------");
}
@Override
public boolean isValid(LengthValidation annotation, Object value) {
if (!(value instanceof String)) {
//不是字符串
throw new DataValidationException(value + "不是字符串");
}
int length = annotation.strLength();
int minLength = annotation.minLength();
int maxLength = annotation.maxLength();
String valueStr = (String) value;
if (length >= 0) {
return ValidationAdaptation.lengthValidation(valueStr, length);
} else if (minLength >= 0 && maxLength >= 0) {
return ValidationAdaptation.intervalLengthValidation(valueStr,minLength,maxLength);
} else if (minLength >= 0) {
return ValidationAdaptation.minLengthValidation(valueStr,minLength);
} else if (maxLength >= 0) {
return ValidationAdaptation.maxLengthValidation(valueStr,maxLength);
}
return true;
}
}
package com.byit.selector;
import com.byit.annotation.annotationselector.MobileNumberVerification;
import com.byit.exception.DataValidationException;
import com.byit.selector.interfaces.ValidationSelector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.byit.adaptation.ValidationAdaptation.checkPhone;
/**
* 手机号校验规则
* @author huangfu
*/
public class MobileNumberVerificationSelector implements ValidationSelector<MobileNumberVerification> {
private static final Logger log = LoggerFactory.getLogger(MobileNumberVerificationSelector.class);
@Override
public void init(MobileNumberVerification annotation, Object value) {
log.info("--------------------------@MobileNumberVerification进入初始化操作------------------------------");
}
@Override
public boolean isValid(MobileNumberVerification annotation, Object value) {
if(value instanceof String){
String valueStr = (String)value;
return checkPhone(valueStr);
}
//不是字符串
throw new DataValidationException(value+"不是字符串");
}
}
package com.byit.selector;
import com.byit.annotation.annotationselector.NotBank;
import com.byit.exception.DataValidationException;
import com.byit.selector.interfaces.ValidationSelector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.byit.adaptation.ValidationAdaptation.dataNotBank;
/**
* @author huangfu
*/
public class NotBankSelector implements ValidationSelector<NotBank> {
private static final Logger log = LoggerFactory.getLogger(NotBankSelector.class);
@Override
public void init(NotBank annotation , Object object) {
log.info("-------------------NotBank注解参数校验初始化-----------------");
}
@Override
public boolean isValid(NotBank annotation, Object value) {
if(value instanceof String){
String valueStr = (String)value;
return dataNotBank(valueStr);
}
//不是字符串
throw new DataValidationException(value+"不是字符串");
}
}
package com.byit.selector;
import com.byit.adaptation.ValidationAdaptation;
import com.byit.annotation.annotationselector.NotNull;
import com.byit.selector.interfaces.ValidationSelector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 对应注解@NotNull注解
* 非空校验器
* @author huangfu
*/
public class NotNullSelector implements ValidationSelector<NotNull> {
private static final Logger log = LoggerFactory.getLogger(NotBankSelector.class);
@Override
public void init(NotNull annotation,Object object) {
log.info("-------------------NotNull注解参数校验初始化-----------------");
}
@Override
public boolean isValid(NotNull annotation, Object value) {
log.info("---------------------@NutNull开始校验---------------------------");
return ValidationAdaptation.dataNotNull(value);
}
}
package com.byit.selector;
import com.byit.annotation.annotationselector.RegularValidation;
import com.byit.exception.DataValidationException;
import com.byit.selector.interfaces.ValidationSelector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.regex.Pattern;
/**
* 正则匹配校验
* @author huangfu
*/
public class RegularValidationSelector implements ValidationSelector<RegularValidation> {
private static final Logger log = LoggerFactory.getLogger(NotBankSelector.class);
@Override
public void init(RegularValidation annotation, Object value) {
log.info("--------------------------------@RegularValidationSelector 初始化-----------------------------");
}
@Override
public boolean isValid(RegularValidation annotation, Object value) {
if(value instanceof String){
String s = annotation.regularStr();
String valueStr = (String)value;
Pattern pattern = Pattern.compile(s);
return pattern.matcher(valueStr).matches();
}
//不是字符串
throw new DataValidationException(value+"不是字符串");
}
}
package com.byit.selector.interfaces;
import java.lang.annotation.Annotation;
/**
* 非空校验选择器接口,所有的校验规则都必须实现此接口
* @author huangfu
*/
public interface ValidationSelector<T extends Annotation> {
/**
* 校验器初始化
* @param annotation
*/
void init(T annotation, Object value);
/**
* 校验器 返回false则失败 抛出异常打印异常信息
* 返回true 放行 继续执行下面的方法
* @param value
* @param annotation
* @return
*/
boolean isValid(T annotation, Object value);
}
package com.byit.utils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Spring工具类
* @author huangfu
*/
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
}
/**
* 获取applicationContext
* @return 返回applicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 通过name获取 Bean.
* @param name
* @return
*/
public static Object getBean(String name){
return getApplicationContext().getBean(name);
}
/**
* 通过class获取Bean.
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
/**
* 通过name,以及Clazz返回指定的Bean
* @param name
* @param clazz
* @param <T>
* @return
*/
public static <T> T getBean(String name,Class<T> clazz){
return getApplicationContext().getBean(name, clazz);
}
}
package com.byit.utils;
import com.byit.adaptation.ValidationAdaptation;
import com.byit.exception.DataValidationException;
import com.byit.validation.impl.ParamValidationImpl;
/**
* 规则校验工具类
* @author huangfu
*/
public class ValidationUtil {
private static final String CLASS_NAME = ValidationUtil.class.getName();
/**
* 非空校验
* @param value
* @param errorMessage
*/
public static void dataNotNull(Object value,String... errorMessage){
String message = errorMessageGenerate("dataNotNull", "value is null",errorMessage);
if(! ValidationAdaptation.dataNotNull(value)){
throw new DataValidationException(message);
}
}
/**
* 空串校验
* @param value
* @param errorMessage
*/
public static void dataNotBank(String value,String... errorMessage){
String message = errorMessageGenerate("dataNotBank", "value is Bank",errorMessage);
if(! ValidationAdaptation.dataNotBank(value)){
throw new DataValidationException(message);
}
}
/**
* 定长字符串校验
* @param value
* @param length
* @param errorMessage
*/
public static void lengthValidation(String value,int length,String... errorMessage){
String message = errorMessageGenerate("lengthValidation", "Length of value not equal to Specified length",errorMessage);
if(! ValidationAdaptation.lengthValidation(value,length)){
throw new DataValidationException(message);
}
}
/**
* 字符串最小长度校验器
* @param value
* @param minLength
* @param errorMessage
*/
public static void minLengthValidation(String value,int minLength,String... errorMessage){
String message = errorMessageGenerate("minLengthValidation", "Length of value Less than Specified length",errorMessage);
if(! ValidationAdaptation.minLengthValidation(value,minLength)){
throw new DataValidationException(message);
}
}
/**
* 字符串最大长度校验器
* @param value
* @param maxLength
* @param errorMessage
*/
public static void maxLengthValidation(String value,int maxLength,String... errorMessage){
String message = errorMessageGenerate("maxLengthValidation", "Length of value more than the Specified length",errorMessage);
if(! ValidationAdaptation.maxLengthValidation(value,maxLength)){
throw new DataValidationException(message);
}
}
/**
* 中国大陆手机号校验
* @param phone
* @param errorMessage
*/
public static void phoneValidation(String phone,String... errorMessage){
String message = errorMessageGenerate("phoneValidation", "Not a standard mobile number",errorMessage);
if(! ValidationAdaptation.checkPhone(phone)){
throw new DataValidationException(message);
}
}
/**
* 隐藏中间四位手机号
* @param phone
* @param errorMessage
* @return
*/
public static String hideMiddleMobile(String phone,String... errorMessage){
phoneValidation(phone,errorMessage);
return ValidationAdaptation.hideMiddleMobile(phone);
}
/**
* 邮箱规则校验
* @param email
* @param errorMessage
*/
public static void emailValidation(String email,String... errorMessage){
String message = errorMessageGenerate("emailValidation", "Email is not a standard mailbox",errorMessage);
if(! ValidationAdaptation.emailValidation(email)){
throw new DataValidationException(message);
}
}
/**
* 实体类校验,校验规则依据实体类内的成员变量注解
* @param object
*/
public static void modelIsAnnotationValidation(Object object){
SpringUtil.getBean(ParamValidationImpl.class).isValidation(object);
}
/**
* 错误信息生成器
* @param errorMessage
* @param methodName
* @param defaultMessage
* @return
*/
private static String errorMessageGenerate(String methodName,String defaultMessage,String... errorMessage){
if(errorMessage.length > 0){
return errorMessage[0];
}
StringBuilder builder = new StringBuilder(CLASS_NAME);
builder.append("#").append(methodName).append(":").append(defaultMessage);
return builder.toString();
}
}
package com.byit.validation;
import java.lang.annotation.Annotation;
/**
* 适配器
* @author huangfu
*/
public class AbstractValidation implements Validation {
@Override
public void isValidation(Annotation annotation, Object object) {
}
@Override
public void isValidation(Object object) {
}
}
package com.byit.validation;
import java.lang.annotation.Annotation;
/**
* 真正的校验实现
* @author huangfu
*/
public interface Validation {
/**
* 这个是不需要验证内部属性是否需要校验,只需要验证其本身是否通过规定校验的
* @param annotation
* @param object
*/
void isValidation(Annotation annotation, Object object);
/**
* 这个是需要验证其内部属性是否通过校验的实现类
* @param object
*/
void isValidation(Object object);
}
package com.byit.validation.impl;
import com.byit.annotation.MetaAnnotation;
import com.byit.exception.DataValidationException;
import com.byit.selector.interfaces.ValidationSelector;
import com.byit.validation.AbstractValidation;
import org.springframework.stereotype.Component;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
/**
* 这个是不需要验证内部属性是否需要校验,只需要验证其本身是否通过规定校验的
* @author huangfu
*/
public class NotParamValidationImpl extends AbstractValidation {
/**
*校验实现
* @param annotation 参数上的注解
* @param value
*/
@Override
public void isValidation(Annotation annotation,Object value){
try{
//获取此注解上的元注解
MetaAnnotation metaAnnotation = annotation.annotationType().getAnnotation(MetaAnnotation.class);
Class<? extends ValidationSelector> validationClass = metaAnnotation.validationClass();
ValidationSelector validationSelector = validationClass.newInstance();
validationSelector.init(annotation,value);
boolean valid = validationSelector.isValid(annotation, value);
//获取注解上的错误信息
//获取本注解上的错误回调方法 获取错误提示信息
Method errorMessage = annotation.getClass().getMethod("errorMessage");
String errorMessageStr = (String)errorMessage.invoke(annotation);
if(!valid){
throw new DataValidationException(errorMessageStr);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
package com.byit.validation.impl;
import com.byit.annotation.MetaAnnotation;
import com.byit.exception.DataValidationException;
import com.byit.selector.interfaces.ValidationSelector;
import com.byit.validation.AbstractValidation;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 这个是需要验证其内部属性是否通过校验的实现类
* @author huangfu
*/
public class ParamValidationImpl extends AbstractValidation {
/**
* 校验实现
* @param object
*/
@Override
public void isValidation(Object object){
try {
//获取的是方法参数的类的对象
Class<?> aClass = object.getClass();
//获取该对象所有的属性
Field[] declaredFields = aClass.getDeclaredFields();
//遍历本对象所有的成员变量
for (int i = 0; i < declaredFields.length; i++) {
//获取属性上所有的注解
Annotation[] annotations = declaredFields[i].getAnnotations();
//如果这个属性没有注解的话就下一个
if(annotations ==null || annotations.length<=0){
continue;
}
/**
* 遍历此属性所有的注解,寻找破解法
*/
for (int j = 0; j < annotations.length; j++) {
//获取这个注解
Class<? extends Annotation> selectorClass = annotations[j].annotationType();
//判断本注解是否存在元注解MetaAnnotation
boolean annotationPresent = selectorClass.isAnnotationPresent(MetaAnnotation.class);
//存在就获取内部属性
if(annotationPresent){
//获取本注解上的错误回调方法 获取错误提示信息
Method errorMessage = annotations[j].getClass().getMethod("errorMessage");
String errorMessageStr = (String)errorMessage.invoke(annotations[j]);
//获取元注解MetaAnnotation
MetaAnnotation annotation = selectorClass.getAnnotation(MetaAnnotation.class);
//获取注解上的元注解指定的本注解所绑定的实现类
Class<? extends ValidationSelector> validationClass = annotation.validationClass();
//创建实例
ValidationSelector validationSelectorImpl = validationClass.newInstance();
//调用校验方法
declaredFields[i].setAccessible(true);
//调用初始化方法
validationSelectorImpl.init(annotations[j],declaredFields[i].get(object));
//调用验证器是否验证成功 false失败 true 成功
boolean valid = validationSelectorImpl.isValid(annotations[j], declaredFields[i].get(object));
if(!valid){
throw new DataValidationException(errorMessageStr);
}
}
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.byit.config.ValidationAuthConfigure
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment