gpt4 book ai didi

java - 带有动态参数的自定义注释

转载 作者:行者123 更新时间:2023-12-01 13:37:09 25 4
gpt4 key购买 nike

这是我的问题:

我有一个注释:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DummyAnnotation {
String dummyParam1();
String dummyParam2();
}

我的服务是:

@Component
public class DummyService {

@DummyAnnotation(dummyParam1="#otp",dummyParam2="#transactionId")
public void dummy(String otp, String transactionId){

}
}

我的方面正在尝试验证两个参数,如果验证不成功则抛出异常:

 @Around(value = "@annotation(annotation)")
public Object verifyOtp(final ProceedingJoinPoint jointPoint, final DummyAnnotation annotation) throws Throwable {
String transactionId = annotation.dummyParam1();
String otp = annotation.dummyParam2();
Boolean otpValid = otpService.verify(transactionId, otp);
if (otpValid) {
return jointPoint.proceed();
}
else {
throw new AuthentificationForteException();
}

}

我怎样才能让它工作,因为 Spring EL 不工作,而在我的方面我有dummyAnnotation.dummyParam1() 等于“#otp”,而不是我的参数 String otp 的值。

提前致谢。

最佳答案

最后我找到了解决方案:

解决方案是实现一个特定的 Spring 表达式解析器。
我将这些声明添加到我的方面:

private ExpressionParser expressionParser = new SpelExpressionParser();
private ParserContext parserContext = new TemplateParserContext();

我改变了检索虚拟值的方式:

@Around(value = "@annotation(annotation)")
public Object verifyOtp(final ProceedingJoinPoint jointPoint, final DummyAnnotation annotation) throws Throwable {

String transactionId = getDummyValue(annotation.dummyParam1(),jointPoint.getArgs());
String otp = getDummyValue(annotation.dummyParam2(),jointPoint.getArgs());

Boolean otpValid = otpService.verify(transactionId, otp);
if (otpValid) {
return jointPoint.proceed();
}
else {
throw new AuthentificationForteException();
}

}

getDummyValue 是解析表达式的方法:

private String getDummyValue(String authExpression,  Object[] args){
Expression expression = expressionParser.parseExpression(authExpression, parserContext);
String value = expression.getValue(new RootObject(args),String.class);
return value;
}


private static class TemplateparserContext implements ParserContext{

@Override
public boolean isTemplate() {
return true;
}

@Override
public String getExpressionPrefix() {
return "#{";
}

@Override
public String getExpressionSuffix() {
return "}";
}

}

protected static class RootObject {

private final Object[] args;

private RootObject(Object[] args) {
super();
this.args = args;
}

public Object[] getArgs() {
return args;
}
}

最后我将我的服务和 DummyAnnotation 的使用更改为:

 @Component
public class DummyService {

@DummyAnnotation(dummyParam1="#{args[0]}",dummyParam2="#{args[1]}")
public void dummy(String otp, String transactionId){

}
}

关于java - 带有动态参数的自定义注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21186435/

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