让自定义注解支持EL表达式解析方法参数
核心:EL表达式解析器 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 import org.aspectj.lang.JoinPoint;import org.aspectj.lang.reflect.MethodSignature;import org.springframework.core.LocalVariableTableParameterNameDiscoverer;import org.springframework.expression.EvaluationContext;import org.springframework.expression.ExpressionParser;import org.springframework.expression.spel.standard.SpelExpressionParser;import org.springframework.expression.spel.support.StandardEvaluationContext;public class AnnotationElParser { private static final ExpressionParser spelExpressionParser = new SpelExpressionParser(); private static final LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer(); public static <T> T parse (Class<T> clazz, JoinPoint joinPoint, String elStr) { Object[] args = joinPoint.getArgs(); String[] params = discoverer.getParameterNames(((MethodSignature) joinPoint.getSignature()).getMethod()); EvaluationContext context = new StandardEvaluationContext(); for (int len = 0 ; len < (params != null ? params.length : 0 ); len++) { context.setVariable(params[len], args[len]); } return spelExpressionParser.parseExpression(elStr).getValue(context, clazz); } }
使用案例 1 2 String name = AnnotationElParser.parse(String.class, joinPoint, "#user.name" ); ArrayList<String> imgList = AnnotationElParser.parse(ArrayList.class, joinPoint, "#imgList" );