让自定义注解支持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;

/**
* 用于Method自定义注解的的EL表达式解析器
* <p>
* Created by surpass.wei@gmail.com on 2021/4/8.
*/
public class AnnotationElParser {
private static final ExpressionParser spelExpressionParser = new SpelExpressionParser();
private static final LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();

/**
* EL表达式解析
*
* @param clazz 返回值类型
* @param joinPoint 切面连接点
* @param elStr EL表达式
* @return 解析结果
*/
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");

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!