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.aspectj.lang.reflect.MethodSignature; import org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint; import org.springframework.core.LocalVariableTableParameterNameDiscoverer; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import java.lang.reflect.Method;
假设 通过@Xxxx注解的value的el表达式获取入参user的info的name值
@Xxxx(value="'p_lock:'+#user.info.name")
public Sting t1(User user){
}
@Aspect public class Test { private final ExpressionParser parser = new SpelExpressionParser(); private final LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer(); @Pointcut("@@annotation(coo.huawei.Knowledge.解析el表达式.Xxxx)") private void testPoint(){}; @Around("testPoint()") public Object xxx(ProceedingJoinPoint point) throws Throwable { String expr="'p_lock:'+#user.info.name"; Method method = ((MethodSignature) point.getSignature()).getMethod(); // T annotation = method.getAnnotation(Xxx.class); Object[] args = point.getArgs(); parse(expr,method,args); return point.proceed(); } /* * 解析el表达式 * @Param expr #{type}.#{#usr.name} * */ private String parse(String expr, Method method, Object[] args) { String[] parameterNames = discoverer.getParameterNames(method); StandardEvaluationContext context = new StandardEvaluationContext(); for (int i = 0; i < parameterNames.length; i++) { context.setVariable(parameterNames[i],args[i]); } return parser.parseExpression(expr).getValue(context,String.class); } }