spring-bootannotationsspring-aspects

Aspect annotation for class


I have a custom annotation, that is handled with AOP in Spring boot. It works perfect when I put it above a method, but when I put it above class I am not able to extract its value :(

Annotation

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

}

Aspect:

@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
    }

}

Solution

  •    signature.getMethod().getDeclaringClass()
                            .getAnnotation(UserAuthorization.class)
    
       @Target({ElementType.TYPE, ElementType.METHOD})