场景: 需要对入参的数据进行校验,添加相关逻辑或日志监控等
实现方式: AOP自定义注解+反射
代码:
MyParam
/** * 描述:注解 * * @author Administrator * @since 2022/7/11 */ @Target(value = {ElementType.METHOD, ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface MyParam { String value() default ""; } 复制代码
MyParamAsp
/** * desc: 具体逻辑 <br> * date: 2022/7/11 * * @author Administrator */ @Slf4j @Aspect @Component public class MyParamAsp { @Pointcut("@annotation(com.zyjournals.web.miniprogram.config.anno.MyParam)") public void controllerAspect() { } @Before("controllerAspect()") public void doBefore() { log.info("===========================>AOP Before"); } /** * desc: aop after <br> * date: 2022/7/11 * * @author Administrator */ @After("controllerAspect()") public void doAfter(JoinPoint joinPoint) throws NoSuchMethodException { log.info("===========================>AOP After"); MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); // 请求的方法参数值 Object[] args = joinPoint.getArgs(); // 请求的方法参数名称 LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer(); String[] paramNames = u.getParameterNames(method); if (args != null && paramNames != null) { String params = ""; for (int i = 0; i < args.length; i++) { params += " " + paramNames[i] + ": " + args[i]; System.out.println("params = " + params); } } } } 复制代码
使用:
@MyParam("flag") public void testAop(String flag , String tag) { log.info("===========================>测试方法执行了"); }