oldwu's Blog - aop
type: channel
link: https://blog.oldwu.top/index.php/tag/aop/
items: spring实现自定义注解切面编程

spring实现自定义注解切面编程
type: item
date: 2022-06-14T15:37:38+08:00
description: spring实现自定义注解切面编程例如要实现在某几个类之后或之前调用一些操作，就可以用到这个1. 创建自定义注解import java.lang.annotation.*; //注解放置的位置，METHOD是放在方法上 @Target(ElementType.METHOD) //注解在哪个阶段执行 @Retention(RetentionPolicy.RUNTIME) //生成文档 @Documented public @interface ElaSearchRefresh { String id() default ""; String className() default ""; }类中只需要写上自己需要的字段即可，后面可以作为传参使用2. 引入注解变量解析util照抄就完了import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.reflect.MethodSignature; import java.lang.reflect.Method; import java.util.Map; /** * 该类的作⽤可以把⽅法上的参数绑定到注解的变量中 * 注解的语法 * 变量名 * #{} * 能解析类似 * "#{sysOperateLogDto.operateType}" */ public class AnnotationResolver { private static AnnotationResolver resolver; public static AnnotationResolver newInstance() { if (resolver == null) { return resolver = new AnnotationResolver(); } else { return resolver; } } /** * 解析注解上的值 * * @param joinPoint 需要解析的字符串 * @param str * @return */ public Object resolver(JoinPoint joinPoint, String str) { if (str == null) return null; Object value = null; //如果匹配上了#则把内容当作变量 if (str.matches("#\\{\\D*\\}")) { String newStr = str.replaceAll("#\\{", "").replaceAll("\\}", ""); if (newStr.contains(".")) {//复杂类型 try { value = complexResolver(joinPoint, newStr); } catch (Exception e) { e.printStackTrace(); } } else { value = simpleResolver(joinPoint, newStr); } } else {//⾮变量 value = str; } return value; } private Object complexResolver(JoinPoint joinPoint, String str) throws Exception { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); String[] names = methodSignature.getParameterNames(); Object[] args = joinPoint.getArgs(); boolean jsonParseFlag = false; if (str.startsWith("$JSON$")){ jsonParseFlag = true; str = str.replace("$JSON$",""); } String[] strs = str.split("\\."); for (int i = 0; i < names.length; i++) { if (strs[0].equals(names[i])) { Object obj = args[i]; if (obj instanceof Map){ return ((Map<?, ?>) obj).get(strs[1]); } //支持json解析 if (obj instanceo…