• 自定义注解结合SpringAop实现权限,参数校验,日志等等功能


    Aop(Aspect Orient Programming)

    使用场景实现一些共性需求:

    1. 收集上报指定一些 重要的关键方法的入参,执行时间返回结果等等关键的信息进行上报到服务器,可以作为后面的调优。
    2. 幂等性的前置校验
    3. 调用重试机制
    4. 入参的共性校验
    5. 方法执行的进行相关扩展行为,记录日志,启动其他任务等等。

    1.参数校验实现

    1. 自定义注解 参数,集合等等校验注解

    1.1 FiledCheck字段校验注解
    package com.eshore.iscm.aop.validate.validator.anno;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Target({ ElementType.PARAMETER, ElementType.FIELD })
    @Retention(RetentionPolicy.RUNTIME)
    public @interface FieldCheck {
    
    	/**
    	 * 参数校验错误默认返回的信息
    	 * 
    	 * @return
    	 */
    	public String defaultMessage() default "";
    
    	/**
    	 * 不允许为空
    	 * 
    	 * @return
    	 */
    	public boolean notNull() default false;
    
    	/**
    	 * 为空时返回信息
    	 * 
    	 * @return
    	 */
    	public String notNullMessage() default "";
    
    	/**
    	 * 只允许数字
    	 * 
    	 * @return
    	 */
    	public boolean numeric() default false;
    	
    	
    
    	/**
    	 * 只允许数字错误信息
    	 * 
    	 * @return
    	 */
    	public String numericMessage() default "";
    	
    	/**
    	 * 字符串只允许输入数字或空串
    	 * 
    	 * @return
    	 */
    	public boolean stringLimitNumeric() default false;
    	
    	
    	/**
    	 * 字符串只允许输入数字或空串
    	 * 
    	 * @return
    	 */
    	public String stringLimitNumericMessage() default "";
    	
    	/**
    	 * 只对字符串、List起效,最小长度
    	 * 
    	 * @return
    	 */
    	public int minLen() default -1;
    
    	/**
    	 * 只对字符串、List起效,最大长度
    	 * 
    	 * @return
    	 */
    	public int maxLen() default -1;
    
    	/**
    	 * maxLen的错误信息
    	 * 
    	 * @return
    	 */
    	public String minLenMessage() default "";
    
    	/**
    	 * maxLen的错误信息
    	 * 
    	 * @return
    	 */
    	public String maxLenMessage() default "";
    
    	/**
    	 * 最小数字
    	 * 
    	 * @return
    	 */
    	public double minNum() default -999999999;
    
    	/**
    	 * 最大数字
    	 * 
    	 * @return
    	 */
    	public double maxNum() default -999999999;
    
    	/**
    	 * minNum错误信息
    	 * 
    	 * @return
    	 */
    	public String minNumMessage() default "";
    
    	/**
    	 * maxNum错误信息
    	 * 
    	 * @return
    	 */
    	public String maxNumMessage() default "";
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    1.2 ListCheck集合校验注解
    package com.eshore.iscm.aop.validate.validator.anno;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Target({ ElementType.PARAMETER, ElementType.FIELD })
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ListCheck {
    
    	public boolean notNull() default false;
    
    	public String notNullMessage() default "";
    
    	public int minLen() default -1;
    
    	public String minLenMessage() default "";
    
    	public int maxLen() default -1;
    
    	public String maxLenMessage() default "";
    
    	public String defaultMessage() default "";
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    1.3方法参数校验注解 ModelCheck
    @Target({ ElementType.METHOD, ElementType.PARAMETER })
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ModelCheck {
    	public boolean notNull() default true;
    
    	public String notNullMessage() default "方法参数不能为空";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    1.4 参数校验注解
    package com.eshore.iscm.aop.validate.validator.anno;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Target({ ElementType.METHOD })
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ParamCheck {
    
    }
    
    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    2.定义Aop并且通过反射进行和注解作用的地方(方法,参数,类)进行关联 反射可以单独写一个类,Aop的配置可以单独写一个类

    2.1通过反射组合上面参数校验的注解灵活使用 (ParamterCheckComp 参数校验组合类)
    package com.eshore.iscm.aop.validate.validator.comp;
    
    import java.lang.annotation.Annotation;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    import java.math.BigDecimal;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
    import org.springframework.stereotype.Component;
    import org.springframework.util.ObjectUtils;
    import org.springframework.util.StringUtils;
    
    import com.eshore.iscm.aop.validate.validator.anno.FieldCheck;
    import com.eshore.iscm.aop.validate.validator.anno.ListCheck;
    import com.eshore.iscm.aop.validate.validator.anno.ModelCheck;
    import com.eshore.khala.common.exception.ValidateParameterException;
    
    @Component
    public class ParamterCheckComp {
    	LocalVariableTableParameterNameDiscoverer disc = new LocalVariableTableParameterNameDiscoverer();
    
    	public void checkValid(String methodName, Object target, Object[] args) throws ValidateParameterException {
    		String str = "";
    		try {
    			Method method = getMethodByClassAndName(target.getClass(), methodName, args);
    			Annotation[][] annotations = method.getParameterAnnotations();
    			String[] paramNames = disc.getParameterNames(method);
    			if (annotations != null) {
    				for (int i = 0; i < annotations.length; i++) {
    					Annotation[] anno = annotations[i];
    					for (int j = 0; j < anno.length; j++) {
    						if (annotations[i][j].annotationType().equals(ModelCheck.class)) {
    							ModelCheck mcheck = (ModelCheck) annotations[i][j];
    							str = checkModel(args[i], mcheck, paramNames[i]);
    						} else if (annotations[i][j].annotationType().equals(ListCheck.class)) {// List
    							ListCheck lcheck = (ListCheck) annotations[i][j];
    							str = checkListParam(args[i], lcheck, paramNames[i]);
    						} else if (annotations[i][j].annotationType().equals(FieldCheck.class)) {// Field
    							FieldCheck fcheck = (FieldCheck) annotations[i][j];
    							str = checkField(fcheck, args[i], paramNames[i]);
    						}
    						if (StringUtils.hasText(str)) {
    							throw new ValidateParameterException(str);
    						}
    					}
    				}
    			}
    		} catch (Throwable e) {
    //			System.out.println(e.getMessage());
    			if (ObjectUtils.isEmpty(str)) {
    				str = e.getMessage();
    			}
    			throw new ValidateParameterException(str);
    		}
    	}
    
    	public void checkValid(ProceedingJoinPoint joinPoint) throws ValidateParameterException {
    		Object[] args = null;
    		Method method = null;
    		Object target = null;
    		String methodName = null;
    		String str = "";
    		try {
    			methodName = joinPoint.getSignature().getName();
    			target = joinPoint.getTarget();
    			args = joinPoint.getArgs(); // 方法的参数
    			method = getMethodByClassAndName(target.getClass(), methodName, args);
    			Annotation[][] annotations = method.getParameterAnnotations();
    			String[] paramNames = disc.getParameterNames(method);
    			if (annotations != null) {
    				for (int i = 0; i < annotations.length; i++) {
    					Annotation[] anno = annotations[i];
    					for (int j = 0; j < anno.length; j++) {
    						if (annotations[i][j].annotationType().equals(ModelCheck.class)) {
    							ModelCheck mcheck = (ModelCheck) annotations[i][j];
    							str = checkModel(args[i], mcheck, paramNames[i]);
    						} else if (annotations[i][j].annotationType().equals(ListCheck.class)) {// List
    							ListCheck lcheck = (ListCheck) annotations[i][j];
    							str = checkListParam(args[i], lcheck, paramNames[i]);
    						} else if (annotations[i][j].annotationType().equals(FieldCheck.class)) {// Field
    							FieldCheck fcheck = (FieldCheck) annotations[i][j];
    							str = checkField(fcheck, args[i], paramNames[i]);
    						}
    						if (StringUtils.hasText(str)) {
    							throw new ValidateParameterException(str);
    						}
    					}
    				}
    			}
    		} catch (Throwable e) {
    //			System.out.println(e.getMessage());
    			throw new ValidateParameterException(str);
    		}
    	}
    
    	private String checkField(FieldCheck check, Object arg, String paramNames) {
    		int length = 0;
    		if (arg == null) {
    			if (check.notNull()) {
    				return getNotNullMessage(paramNames, check);
    			} else if (check.numeric()) {
    				return getNumericMessage(paramNames, check);
    			} else if (check.minLen() > 0) {
    				return getMinLenMessage(paramNames, check);
    			} else if (check.maxLen() > 0) {
    				return getMaxLenMessage(paramNames, check);
    			} else if (check.minNum() != -999999999) {
    				return getMinNumMessage(paramNames, check, false);
    			} else if (check.maxNum() != -999999999) {
    				return getMaxNumMessage(paramNames, check, false);
    			} else {
    				return "";
    			}
    		}
    		Class<?> cls = arg.getClass();
    		String clname = cls.getName();
    //        System.out.println("field-class: " + cls.getName());
    		boolean arraybl = false, strbl = false, intbl = false, longbl = false, doublebl = false, floatbl = false,
    				blbl = false;
    		// 判断是否为数字
    		if (clname.equals("java.lang.Integer") || clname.equals("int")) {
    			intbl = true;
    		} else if (clname.equals("java.lang.Long") || clname.equals("long")) {
    			longbl = true;
    		} else if (clname.equals("java.lang.Double") || clname.equals("double")) {
    			doublebl = true;
    		} else if (clname.equals("java.lang.Float") || clname.equals("float")) {
    			floatbl = true;
    		} else if (clname.equals("java.lang.String")) {// 判断是否为字符串
    			strbl = true;
    		} else if (clname.equals("java.util.ArrayList")) {
    			// 判断是否为List
    			arraybl = true;
    		} else if (clname.equals("java.util.Boolean")) {// 判断是否为Boolean
    			blbl = true;
    		}
    
    		boolean numbl = intbl || longbl || floatbl || doublebl;
    		boolean lenbl = arraybl || strbl;
    		if (arg != null) {
    			if (strbl)
    				length = (String.valueOf(arg)).length();
    			if (arraybl)
    				length = ((List<Object>) arg).size();
    		}
    
    		if (check.numeric() && arg != null) {
    			try {
    				new BigDecimal(String.valueOf(arg));
    			} catch (Exception e) {
    				return getNumericMessage(paramNames, check);
    			}
    		}
    		if (lenbl) {
    			if (check.maxLen() > 0 && (length > check.maxLen())) {
    				return getMaxLenMessage(paramNames, check);
    			}
    
    			if (check.minLen() > 0 && (length < check.minLen())) {
    				return getMinLenMessage(paramNames, check);
    			}
    		}
    		if (numbl) {
    			if (check.minNum() != -999999999) {
    				try {
    					boolean errbl = false;
    					if (longbl || intbl) {
    						long fieldValue = Long.parseLong(String.valueOf(arg));
    						if (fieldValue < check.minNum()) {
    							errbl = true;
    						}
    					}
    					if (floatbl || doublebl) {
    						double fieldValue = Double.parseDouble(String.valueOf(arg));
    						if (fieldValue < check.minNum()) {
    							errbl = true;
    						}
    					}
    					if (errbl) {
    						return getMinNumMessage(paramNames, check, false);
    					}
    				} catch (Exception e) {
    					return getMinNumMessage(paramNames, check, true);
    				}
    			}
    
    			if (check.maxNum() != -999999999) {
    				try {
    					boolean errbl = false;
    					if (longbl || intbl) {
    						long fieldValue = Long.parseLong(String.valueOf(arg));
    						if (fieldValue > check.maxNum()) {
    							errbl = true;
    						}
    					} else if (floatbl || doublebl) {
    						double fieldValue = Double.parseDouble(String.valueOf(arg));
    						if (fieldValue > check.maxNum()) {
    							errbl = true;
    						}
    					}
    					if (errbl) {
    						return getMaxNumMessage(paramNames, check, false);
    					}
    				} catch (Exception e) {
    					return getMaxNumMessage(paramNames, check, true);
    				}
    			}
    		}
    
    		// if(arraybl){
    		// checkListParam(args, lcheck)
    		// }
    		return "";
    	}
    
    	/**
    	 * 校验List入参
    	 *
    	 * @param args
    	 * @param lcheck
    	 * @param paramNames
    	 * @return
    	 * @throws Exception
    	 */
    	private String checkListParam(Object args, ListCheck lcheck, String paramNames) throws Exception {
    		String retStr = "";
    		if (args == null) {
    			if (lcheck.notNull()) {
    				if (lcheck.notNullMessage().equals("")) {
    					return paramNames + "不允许为空";
    				} else {
    					return lcheck.defaultMessage();
    				}
    			} else if (lcheck.maxLen() != -1) {
    				if (lcheck.defaultMessage().equals("")) {
    					return paramNames + "不允许为空";
    				} else {
    					return lcheck.defaultMessage();
    				}
    			} else if (lcheck.minLen() != -1) {
    				if (lcheck.minLenMessage().equals("")) {
    					return paramNames + "不允许为空";
    				} else {
    					return lcheck.defaultMessage();
    				}
    			}
    		}
    		if (args != null) {
    			String aclz = args.getClass().getName();
    //			System.out.println("args-class: " + aclz);
    			if (aclz.equals("java.util.ArrayList")) {
    				List<Object> argList = (List<Object>) args;
    				int size = argList.size();
    				if (lcheck.minLen() != -1) {
    					if (size < lcheck.minLen()) {
    						retStr = lcheck.minLenMessage();
    						if (retStr.equals("")) {
    							retStr = lcheck.defaultMessage();
    						}
    						if (retStr.equals("")) {
    							retStr = paramNames + "集合大小最小为" + lcheck.minLen();
    						}
    						return retStr;
    					}
    				}
    				if (lcheck.maxLen() != -1) {
    					if (size < lcheck.maxLen()) {
    						retStr = lcheck.maxLenMessage();
    						if (retStr.equals("")) {
    							retStr = lcheck.defaultMessage();
    						}
    						if (retStr.equals("")) {
    							retStr = paramNames + "集合大小最大为" + lcheck.maxLen();
    						}
    						return retStr;
    					}
    				}
    				// else
    				for (Object arg : argList) {
    					if (arg != null) {
    						retStr = checkModel(arg, null, "");
    					}
    					if (!retStr.equals("")) {
    						break;
    					}
    				}
    			}
    		}
    
    		return retStr;
    	}
    
    	/**
    	 * 校验参数
    	 *
    	 * @param args
    	 * @param mcheck
    	 * @param paramNames
    	 * @return
    	 * @throws Exception
    	 */
    	private String checkModel(Object args, ModelCheck mcheck, String paramNames) throws Exception {
    		String retStr = "";
    		if (args == null 
    				|| (args instanceof String) && "".equals(String.valueOf(args))
    				|| (args instanceof Object[]) && ((Object[]) args).length == 0) {
    			if (mcheck.notNull()) {
    				if (mcheck.notNullMessage().equals("")) {
    					return paramNames + "不允许为空";
    				} else {
    					return mcheck.notNullMessage();
    				}
    			}
    			return "";
    		}
    		Field[] field = getBeanFields(args);// 获取实体及父类的field
    		// args.getClass().getDeclaredFields();// 获取方法参数(实体)的field
    		for (int j = 0; j < field.length; j++) {
    			FieldCheck check = field[j].getAnnotation(FieldCheck.class);// 获取方法参数(实体)的field上的注解Check
    			if (check != null) {
    				retStr = validateFiled(check, field[j], args);
    				if (StringUtils.hasText(retStr)) {
    					return retStr;
    				}
    			} else {
    				ListCheck lcheck = field[j].getAnnotation(ListCheck.class);
    				if (lcheck != null) {
    					field[j].setAccessible(true);
    					retStr = checkListParam(field[j].get(args), lcheck, field[j].getName());
    					if (StringUtils.hasText(retStr)) {
    						return retStr;
    					}
    				}
    			}
    		}
    		return retStr;
    	}
    
    	public Field[] getBeanFields(Object obj) {
    		List<Field> fieldList = new ArrayList<>();
    		Class<?> tmp = obj.getClass();
    		while (tmp != null && tmp instanceof Object) {
    			fieldList.addAll(Arrays.asList(tmp.getDeclaredFields()));
    			tmp = tmp.getSuperclass();
    		}
    		return fieldList.toArray(new Field[fieldList.size()]);
    	}
    
    	/**
    	 * 校验参数规则
    	 *
    	 * @param check
    	 * @param field
    	 * @param args
    	 * @return
    	 * @throws Exception
    	 */
    	public String validateFiled(FieldCheck check, Field field, Object args) throws Exception {
    		field.setAccessible(true);
    		// 获取field长度
    		int length = 0;
    		Class<?> cls = field.getType();
    		String clname = cls.getName();
    //		System.out.println("field-class: " + cls.getName());
    		boolean arraybl = false, strbl = false, intbl = false, longbl = false, doublebl = false, floatbl = false,
    				blbl = false;
    		// 判断是否为数字
    		if (clname.equals("java.lang.Integer") || clname.equals("int")) {
    			intbl = true;
    		} else if (clname.equals("java.lang.Long") || clname.equals("long")) {
    			longbl = true;
    		} else if (clname.equals("java.lang.Double") || clname.equals("double")) {
    			doublebl = true;
    		} else if (clname.equals("java.lang.Float") || clname.equals("float")) {
    			floatbl = true;
    		} else if (clname.equals("java.lang.String")) {// 判断是否为字符串
    			strbl = true;
    		} else if (clname.equals("java.util.ArrayList")) {
    			// 判断是否为List
    			arraybl = true;
    		} else if (clname.equals("java.util.Boolean")) {// 判断是否为Boolean
    			blbl = true;
    		}
    
    		boolean numbl = intbl || longbl || floatbl || doublebl;
    		boolean lenbl = arraybl || strbl;
    		if (field.get(args) != null) {
    			if (strbl)
    				length = (String.valueOf(field.get(args))).length();
    			if (arraybl)
    				length = ((List<Object>) field.get(args)).size();
    		}
    		if (check.notNull()) {
    			if (field.get(args) == null || "".equals(String.valueOf(field.get(args)))) {
    				return getNotNullMessage(field.getName(), check);
    			}
    		}
    
    		if (check.numeric() && field.get(args) != null) {
    			try {
    				new BigDecimal(String.valueOf(field.get(args)));
    			} catch (Exception e) {
    				return getNumericMessage(field.getName(), check);
    			}
    		}
    		
    		
    		if (check.stringLimitNumeric() && field.get(args) != null) {
    			try {
    				if(!StringUtils.isEmpty(String.valueOf(field.get(args)))){
    					new BigDecimal(String.valueOf(field.get(args)));
    				}
    			} catch (Exception e) {
    				return getStringLimitNumericMessage(field.getName(), check);
    			}
    		}
    		// spring mvc 默认会把null值设置成false,json非true | false 请求出错
    		// 此处判定无用
    		/*
    		 * if (blbl) { try { Boolean.parseBoolean(String.valueOf(field.get(args))); }
    		 * catch (Exception e) { if (check.defaultMessage().length() > 0) { return
    		 * check.defaultMessage(); } else { return field.getName() + "必须为true或者false"; }
    		 * } }
    		 */
    		if (lenbl) {
    			if (check.maxLen() > 0 && (length > check.maxLen())) {
    				return getMaxLenMessage(field.getName(), check);
    			}
    
    			if (check.minLen() > 0 && (length < check.minLen())) {
    				return getMinLenMessage(field.getName(), check);
    			}
    		}
    		if (numbl) {
    			if (check.minNum() != -999999999) {
    				try {
    					boolean errbl = false;
    					if (longbl || intbl) {
    						long fieldValue = Long.parseLong(String.valueOf(field.get(args)));
    						if (fieldValue < check.minNum()) {
    							errbl = true;
    						}
    					}
    					if (floatbl || doublebl) {
    						double fieldValue = Double.parseDouble(String.valueOf(field.get(args)));
    						if (fieldValue < check.minNum()) {
    							errbl = true;
    						}
    					}
    					if (errbl) {
    						return getMinNumMessage(field.getName(), check, false);
    					}
    				} catch (Exception e) {
    					return getMinNumMessage(field.getName(), check, true);
    				}
    			}
    
    			if (check.maxNum() != -999999999) {
    				try {
    					boolean errbl = false;
    					if (longbl || intbl) {
    						long fieldValue = Long.parseLong(String.valueOf(field.get(args)));
    						if (fieldValue > check.maxNum()) {
    							errbl = true;
    						}
    					} else if (floatbl || doublebl) {
    						double fieldValue = Double.parseDouble(String.valueOf(field.get(args)));
    						if (fieldValue > check.maxNum()) {
    							errbl = true;
    						}
    					}
    					if (errbl) {
    						return getMaxNumMessage(field.getName(), check, false);
    					}
    				} catch (Exception e) {
    					return getMaxNumMessage(field.getName(), check, true);
    				}
    			}
    		}
    
    		// if(arraybl){
    		// checkListParam(args, lcheck)
    		// }
    		return "";
    	}
    
    	private String getMaxNumMessage(String name, FieldCheck check, boolean err) {
    		if (check.maxNumMessage().length() > 0) {
    			return check.maxNumMessage();
    		}
    		if (check.defaultMessage().length() > 0) {
    			return check.defaultMessage();
    		}
    		if (!err)
    			return name + "必须不大于" + check.maxNum();
    		else
    			return name + "必须为数值型,且不大于" + check.maxNum();
    	}
    
    	private String getMinNumMessage(String name, FieldCheck check, boolean err) {
    		if (check.minNumMessage().length() > 0) {
    			return check.minNumMessage();
    		}
    		if (check.defaultMessage().length() > 0) {
    			return check.defaultMessage();
    		}
    		if (!err)
    			return name + "必须不小于" + check.minNum();
    		else
    			return name + "必须为数值型,且不小于" + check.minNum();
    	}
    
    	private String getMinLenMessage(String name, FieldCheck check) {
    		if (check.minLenMessage().length() > 0) {
    			return check.minLenMessage();
    		}
    		if (check.defaultMessage().length() > 0) {
    			return check.defaultMessage();
    		}
    		return name + "长度不能小于" + check.minLen();
    	}
    
    	private String getMaxLenMessage(String name, FieldCheck check) {
    		if (check.maxLenMessage().length() > 0) {
    			return check.maxLenMessage();
    		}
    		if (check.defaultMessage().length() > 0) {
    			return check.defaultMessage();
    		}
    		return name + "长度不能大于" + check.maxLen();
    	}
    
    	private String getNumericMessage(String name, FieldCheck check) {
    		if (check.numericMessage().length() > 0) {
    			return check.numericMessage();
    		}
    		if (check.defaultMessage().length() > 0) {
    			return check.defaultMessage();
    		}
    		return name + "必须为数值型";
    	}
    	
    	private String getStringLimitNumericMessage(String name, FieldCheck check) {
    		if (check.stringLimitNumericMessage().length() > 0) {
    			return check.stringLimitNumericMessage();
    		}
    		if (check.defaultMessage().length() > 0) {
    			return check.defaultMessage();
    		}
    		return name + "必须为空串或数值型";
    	}
    
    	private String getNotNullMessage(String fieldName, FieldCheck check) {
    		if (check.notNullMessage().length() > 0) {
    			return check.notNullMessage();
    		}
    		if (check.defaultMessage().length() > 0) {
    			return check.defaultMessage();
    		}
    		return fieldName + "不能为空";
    	}
    
    	/**
    	 * 根据类和方法名得到方法
    	 *
    	 * @param args
    	 */
    	@SuppressWarnings("rawtypes")
    	public Method getMethodByClassAndName(Class c, String methodName, Object[] args) throws Exception {
    		boolean pbl = true;
    		if (args != null && args.length > 0) {
    			Class<?>[] parameterTypes = new Class<?>[args.length];
    			if (args != null && args.length > 0) {
    				int i = 0;
    				for (Object obj : args) {
    					if (obj != null) {
    						Class<?> clz = obj.getClass();
    						if (clz.getName().equals("java.util.ArrayList")) {
    							clz = List.class;
    						}
    						parameterTypes[i++] = clz;
    					} else {
    						pbl = false;
    						break;
    					}
    				}
    				if (pbl) {
    					return c.getDeclaredMethod(methodName, parameterTypes);
    				}
    			}
    		}
    
    		Method[] methods = c.getDeclaredMethods();
    		for (Method method : methods) {
    			if (method.getName().equals(methodName)) {
    				if (args != null) {
    					if (method.getParameterCount() == args.length) {
    						return method;
    					}
    				} else {
    					return method;
    				}
    			}
    		}
    		return null;
    	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
    • 354
    • 355
    • 356
    • 357
    • 358
    • 359
    • 360
    • 361
    • 362
    • 363
    • 364
    • 365
    • 366
    • 367
    • 368
    • 369
    • 370
    • 371
    • 372
    • 373
    • 374
    • 375
    • 376
    • 377
    • 378
    • 379
    • 380
    • 381
    • 382
    • 383
    • 384
    • 385
    • 386
    • 387
    • 388
    • 389
    • 390
    • 391
    • 392
    • 393
    • 394
    • 395
    • 396
    • 397
    • 398
    • 399
    • 400
    • 401
    • 402
    • 403
    • 404
    • 405
    • 406
    • 407
    • 408
    • 409
    • 410
    • 411
    • 412
    • 413
    • 414
    • 415
    • 416
    • 417
    • 418
    • 419
    • 420
    • 421
    • 422
    • 423
    • 424
    • 425
    • 426
    • 427
    • 428
    • 429
    • 430
    • 431
    • 432
    • 433
    • 434
    • 435
    • 436
    • 437
    • 438
    • 439
    • 440
    • 441
    • 442
    • 443
    • 444
    • 445
    • 446
    • 447
    • 448
    • 449
    • 450
    • 451
    • 452
    • 453
    • 454
    • 455
    • 456
    • 457
    • 458
    • 459
    • 460
    • 461
    • 462
    • 463
    • 464
    • 465
    • 466
    • 467
    • 468
    • 469
    • 470
    • 471
    • 472
    • 473
    • 474
    • 475
    • 476
    • 477
    • 478
    • 479
    • 480
    • 481
    • 482
    • 483
    • 484
    • 485
    • 486
    • 487
    • 488
    • 489
    • 490
    • 491
    • 492
    • 493
    • 494
    • 495
    • 496
    • 497
    • 498
    • 499
    • 500
    • 501
    • 502
    • 503
    • 504
    • 505
    • 506
    • 507
    • 508
    • 509
    • 510
    • 511
    • 512
    • 513
    • 514
    • 515
    • 516
    • 517
    • 518
    • 519
    • 520
    • 521
    • 522
    • 523
    • 524
    • 525
    • 526
    • 527
    • 528
    • 529
    • 530
    • 531
    • 532
    • 533
    • 534
    • 535
    • 536
    • 537
    • 538
    • 539
    • 540
    • 541
    • 542
    • 543
    • 544
    • 545
    • 546
    • 547
    • 548
    • 549
    • 550
    • 551
    • 552
    • 553
    • 554
    • 555
    • 556
    • 557
    • 558
    • 559
    • 560
    • 561
    • 562
    • 563
    • 564
    • 565
    • 566
    • 567
    • 568
    • 569
    • 570
    • 571
    • 572
    • 573
    • 574
    • 575
    • 576
    • 577
    • 578
    • 579
    • 580
    • 581
    • 582
    • 583
    • 584
    • 585
    • 586
    • 587
    • 588
    • 589
    • 590
    • 591
    • 592
    • 593
    • 594
    • 595
    • 596
    • 597
    • 598
    • 599
    • 600
    • 601
    • 602
    • 603
    • 604
    • 605
    • 606
    • 607
    • 608
    • 609
    • 610
    • 611
    • 612

    3.在SpringBoot上面配置上Aop进行拦截实现

    3.1 Aop的5大通知,在什么地方进行拦截的通知
    1. @Before前置通知 方法执行之前进行执行
    2. @AfterReturning: 当前通知方法在原始切入点方法正常执行完毕后运行
    3. @AfterThrowing: 当前通知方法在原始切入点方法运行抛出异常后执行
    4. @Around: 设置当前通知方法与切入点之间的绑定关系,当前通知方法在原始切入点方法前后运行 最强大的通知类型,可以对方法的入参,执行,返回结果等和方面细节进行调节
    5. @After: 当前通知方法在原始切入点方法后运行
    package com.eshore.iscm.aop.validate.validator.asp;
    
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Pointcut;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    import com.eshore.iscm.aop.validate.validator.comp.ParamterCheckComp;
    
    @Component
    @Aspect
    public class ParamAspect {
    	@Autowired
    	private ParamterCheckComp paramterCheckComp;
    
    	@Pointcut("@annotation(com.eshore.iscm.aop.validate.validator.anno.ParamCheck)")
    	public void check() {
    
    	}
    
    	@Around(value = "check()")
    	public Object doBefore(JoinPoint joinPoint) throws Throwable {
    		Object object = null;
    		// 参数校验,未抛出异常表示验证OK
    //		long st = System.currentTimeMillis();
    		paramterCheckComp.checkValid(joinPoint.getSignature().getName(), joinPoint.getTarget(), joinPoint.getArgs());
    //		System.out.println("doBefore use time mills: " + (System.currentTimeMillis() - st));
    		object = ((ProceedingJoinPoint) joinPoint).proceed();
    		return object;
    	}
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    4. 自定义的注解的使用FieldCheck可以作用在字段上面

    package com.eshore.iscm.common.model;
    
    import javax.validation.constraints.Min;
    
    import com.eshore.iscm.aop.validate.validator.anno.FieldCheck;
    
    import io.swagger.annotations.ApiModelProperty;
    import lombok.Data;
    
    /**
     * 分页查询参数需要继承
     */
    @Data
    public class PageParam {
    
    	@ApiModelProperty(value = "当前页", required = true)
    	@Min(value = 0, message = "当前页最小为1")
    	@FieldCheck(notNull = true, notNullMessage = "page属性不允许为空", minNum = 1, minNumMessage = "页码最小为1")
    	protected Integer page;
    	
    	@ApiModelProperty(value = "每页显示条数", required = true)
    	@Min(value = 1, message = "每页显示条数最小为1")
    	@FieldCheck(notNull = true, notNullMessage = "limit属性不允许为空", minNum = 1, minNumMessage = "页显示条数最小为1")
    	protected Integer limit;
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    5. ModelCheck 参数使用

    	@ParamCheck
    	@ApiOperation(value = "删除广告", notes = "删除广告")
    	@PostMapping("/delete")
        public Result<String> delete(@RequestParam("advertisementIds") @ModelCheck(notNull = true) String[] advertisementIds) {
            log.info(getClass().getSimpleName() + "#delete param:{}", JsonUtil.toJSONString(advertisementIds));
            try {
            	advertisementService.deleteByIds(advertisementIds);
            	return Result.succeed("删除成功");
            } catch (Exception e) {
                log.error("delete error!", e);
                return Result.failed(e.getMessage());
            }
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    2. 权限校验实现

    注意:权限校验需要在方法执行之前进行相关的校验,也就是使用前置通知进行 @Before

    1. 自定义注解

    package com.eshore.iscm.aop.validate.validator.anno;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.ANNOTATION_TYPE,ElementType.METHOD})
    public @interface Authenticat {
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2. 使用Aop并且用反射进行拦截

    package com.eshore.iscm.aop.validate.validator.asp;
    
    import com.eshore.iscm.aop.validate.validator.anno.Authenticat ;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.aspectj.lang.annotation.Pointcut;
    import org.aspectj.lang.reflect.MethodSignature;
    import org.springframework.stereotype.Component;
    
    import java.lang.reflect.Method;
    import java.util.HashSet;
    
    @Aspect
    @Component
    public class AuthAspect {
        @Pointcut("@annotation()")
        public void pointCut(){
    
        }
    
        @Before("pointCut()")
        public void dobefore(JoinPoint joinPoint){
            /*
            * 数据库查询 你的所有权限可以放在一个set集合里面
            *
            * */
            HashSet<User> sets = new HashSet<User>();
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    
            Method method = signature.getMethod();
    
            Authenticat  annotation = method.getAnnotation(Authenticat .class);
    
            if(annotation != null && !sets.contains(annotation.value()) ){
                throw new RuntimeException("用户没有权限进行访问!!!")
    
    
            }
    
        }
    }
    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    对你有帮助别忘记点赞一个呦,点赞敲代码没有bug,今年马上找到女朋友,哈哈!!,当然更加重要的是可以评论一下你们面试当中遇到的相关AOp的知识,欢迎大家在评论区中打出你们遇到Aop的相关的坑!!!和对Aop的相关理解。
  • 相关阅读:
    自己动手写线程池——向JDK线程池进发
    Selenium浏览器自动化测试框架
    机械臂B样条插补+带源代码
    Python_15 ddt驱动与日志
    国庆作业1
    xray:漏洞扫描利器
    即时分账系统对B2B电商业务的重要性?
    Redis数据持久化
    VR航天科普体验馆VR航空馆规划遨游太空感受其中乐趣
    ksdbmerge.tools All Product Crack
  • 原文地址:https://blog.csdn.net/houzhicongone/article/details/127817588