class 的方面注释

Aspect annotation for class

我有一个自定义注释,它在 Spring 启动时使用 AOP 处理。当我把它放在方法上面时,它工作得很好,但是当我把它放在 class 上面时,我无法提取它的值:(

注释

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserAuthorization {
    
    UserRoleEnum[] userRoles();
    
    String paramName() default "userDetails";
    
    String errorMessage() default "NOT AUTHORIZED";

}

看点:

@Aspect
@Component
public class UserAuthorizationAspect {

    @Around("@annotation(UserAuthorization)")
    public Object validateAuthoritiesAspect(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        UserAuthorization userAuthorization = signature.getMethod().getAnnotation(UserAuthorization.class);
        // Some code
    }

}
  • 更改你的外观以检查 class 是否有注释
   signature.getMethod().getDeclaringClass()
                        .getAnnotation(UserAuthorization.class)
  • 更改注释以支持 class 级别和方法级别的注释
   @Target({ElementType.TYPE, ElementType.METHOD})