![](/img/trans.png)
[英]Java EE CDI Interceptor not working when annotation has parameters
[英]Java: Get annotation parameters for interceptor from InvocationContext
我有一个使用 Quarkus 的 REST API,我想在其中编写一个拦截器,它为 API 中的每个端点获取不同的参数。 基本上我想提供字符串并查看它们是否在请求附带的 JWT 中。 我很难根据需要获取参数,作为字符串。
这是注释:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import javax.enterprise.util.Nonbinding;
import javax.interceptor.InterceptorBinding;
@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface ScopesAllowed {
@Nonbinding
String[] value();
}
这是使用它的一个端点:
import javax.ws.rs.GET;
import java.util.List;
public class TenantResource {
@GET
@ScopesAllowed({"MyScope", "AnotherScope"})
public List<Tenant> getTenants() {
}
}
这是我对拦截器的尝试:
@Interceptor
@Priority(3000)
@ScopesAllowed({})
public class ScopesAllowedInterceptor {
@Inject
JsonWebToken jwt;
@AroundInvoke
public Object validate(InvocationContext ctx) throws Exception {
// get annotation parameters and check JWT
return ctx.proceed();
//or
throw new UnauthorizedException();
}
}
让我感到困惑的是当我尝试System.out.println(ctx.getContextData());
我得到:
{io.quarkus.arc.interceptorBindings=[@mypackage.annotations.ScopesAllowed(value={"MyScope", "AnotherScope"})]}
因此值在那里,但我不知道如何处理这种类型的 object。 它是 Map<String, Object> 类型,但我不知道如何处理 object 以实际获取大括号中的值。 我不想做 toString() 然后一些奇怪的字符串操作来获取它们。
我试图对此进行研究,但我没有找到解决方案,我现在不知道去哪里找。
使用InvicationContext#getMethod()
获取被调用的Method
,然后获取该方法的注解。 您可以使用Method#getAnnotations()
获取所有注释,也可以使用Method.getAnnotation(Class<> annotationCls)
Method getTenants = ctx.getMethod();
ScopesAllowed scopesAnnotation = getTenants.getAnnotation(ScopesAllowed.class);
if (scopesAnnotation != null) {
String[] scopesAllowed = scopesAnnotation.value();
}
就是这样,真的不难。 在某些情况下,反射确实可以起到拯救作用。 这是一个很好的工具,可以放在你的工具带下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.