曹耘豪的博客

Spring之Spel表达式

解析Spel工具类

SpelUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class SpelUtils {

private static final SpelExpressionParser parser = new SpelExpressionParser();
private static final DefaultParameterNameDiscoverer nameDiscoverer = new DefaultParameterNameDiscoverer();

public static Object parseValue(String spel, Method method, Object[] args) {

String[] parameterNames = nameDiscoverer.getParameterNames(method);
if (parameterNames == null) {
return null;
}

EvaluationContext context = new StandardEvaluationContext();
for (int i = 0; i < args.length; i++) {
context.setVariable(parameterNames[i], args[i]);
}

Expression expression = parser.parseExpression(spel);

return expression.getValue(context);
}

}

注解与Aspect定义

aspect
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnn {
String keyExpression();
}


@Around("@annotation(config)")
public Object around(ProceedingJoinPoint joinPoint, MyAnn config) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Object value = SpelUtils.parseValue(config.keyExpression(), signature.getMethod(), joinPoint.getArgs());
// ...
}

使用

1
2
3
4
@MyAnn(keyExpression = "'abc' + #bar")
void foo(String bar) {
// 如果入参bar="def",则在aspect里拿到的value是"abcdef"
}
   /