Search code examples
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

    • Change your aspect to check if the class has annotation
       signature.getMethod().getDeclaringClass()
                            .getAnnotation(UserAuthorization.class)
    
    • Change you annotation to support both class level and method level annotations
       @Target({ElementType.TYPE, ElementType.METHOD})