gpt4 book ai didi

java - 如何使用 SpEL 设置注释字段来处理值

转载 作者:行者123 更新时间:2023-12-02 01:03:12 26 4
gpt4 key购买 nike

我需要在带注释的接口(interface)中设置一些字段以接受 Spring 表达式语言定义。

我有一个工作代码,但我对此不满意。请参阅:

注释:

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Example {
String id();
}

方面:

@Aspect
@Component
public class ExampleAspect {
@Before("@annotation(com.example.annotation.Example)")
public void beforeAdvice(JoinPoint joinPoint) {

MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Example p = signature.getMethod().getAnnotation(Example.class);
long id = (Long) valueFromExpression(joinPoint, p.id());
// .... work with ID
}

/**
* Manually processed SpEL expression
*/
private Object valueFromExpression(JoinPoint joinPoint, String expression) {
ExpressionParser parser = new SpelExpressionParser();

StandardEvaluationContext context = new StandardEvaluationContext();
CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();
String[] parameterNames = codeSignature.getParameterNames();
Object[] args = joinPoint.getArgs();

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

Expression exp = parser.parseExpression(expression);

return exp.getValue(context);
}
}

用法:

@GetMapping("/test/{someId}")
@Example(id = "#someId")
public void example(@PathVariable Long someId) {
// some code
}

这可行,但我想将注释属性的初始化定义为由 SpEL 自动处理,并由我的 IDE 正确突出显示 - 没有方法 valueFromExpression()

最佳答案

关于 IDE 支持,请参阅 [@StéphaneNic​​oll] 的回答:https://stackoverflow.com/a/33298418/3759414

"The support in Intellij is the same thing. Currently Jetbrains devs track the places where SpEL is used and mark them for SpEL support. We don't have any way to conduct the fact that the value is an actual SpEL expression (this is a raw java.lang.String on the annotation type after all)."

关于java - 如何使用 SpEL 设置注释字段来处理值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57755042/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com