Spring AOP:如何获取建议方法的注释


问题内容

我想用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代理的内容,但我不希望使用此代理。


问题答案:

我认为@Restricted是您的注释。如果是这种情况,请确保您具有:

@Retention(RetentionPolicy.RUNTIME)

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