春季AOP:如何获得建议方法的注释

2022-09-04 05:10:51

我想用Spring/AOP和注释来实现声明性安全性。正如您在下一个代码示例中看到的那样,我有带有参数“allowedRoles”的受限注释,用于定义允许谁执行建议的方法。

    @Restricted(allowedRoles="jira-administrators")
        public void setPassword(...) throws UserMgmtException {             
               // set password code
               ...
        }

现在,问题是在我的建议中,我无法访问定义的注释:

public Object checkPermission(ProceedingJoinPoint pjp) throws Throwable {

    Signature signature = pjp.getSignature();
    System.out.println("Allowed:" + rolesAllowedForJoinPoint(pjp));
            ...
}

private Restricted rolesAllowedForJoinPoint(ProceedingJoinPoint thisJoinPoint)
        {
            MethodSignature methodSignature = (MethodSignature) thisJoinPoint.getSignature();
            Method targetMethod = methodSignature.getMethod();

            return targetMethod.getAnnotation(Restricted.class);
        }

上述方法始终返回 null(根本没有找到任何注释)。有没有一个简单的解决方案?

我读到了一些关于使用AspectJ代理的内容,但我宁愿不使用此代理。


答案 1

对于在将注释保留更改为运行时仍然遇到问题的人来说,您可能遇到了与我相同的问题:getMethod() 返回接口方法而不是实现类。因此,如果您在类中有注释,那么接口方法上的getAnnotations()自然会返回null。

以下解决方案解决了此问题:

final String methodName = pjp.getSignature().getName();
final MethodSignature methodSignature = (MethodSignature)pjp.getSignature();
Method method = methodSignature.getMethod();
if (method.getDeclaringClass().isInterface()) {
    method = pjp.getTarget().getClass().getDeclaredMethod(methodName, method.getParameterTypes());    
}

如果您愿意,您也可以选择在此处处理接口注释。

此处提供了更多注释:从 ProceedingJoinPoint 获取模板方法实例

奥雷格


答案 2

我假设是你的注释。如果是这种情况,请确保您有:@Restricted

@Retention(RetentionPolicy.RUNTIME)

在注释定义中。这意味着注释在运行时保留。