简体   繁体   中英

Unable to detect class level custom annotation in Spring AOP

I am trying to intercept classes in Spring with following settings

Interceptor

@Aspect
@Component
public class MyInterceptor {

    @Around("execution(* com.example.services..*(..))")
    public Object intercept(ProceedingJoinPoint pjp) throws Throwable {
        if (pjp.getTarget() != null && pjp.getTarget().getClass().getAnnotation(MyAnnotation.class) != null) {
            System.out.println("Yes annotation present");
        } else {
            System.out.println("Annotation not present");
        }

        return = pjp.proceed();
    }   
}

and the class being intercepted is as follows

@Component
@MyAnnotation
public class MyAlert implements IAlert {

}

Every thing is working fine until and unless I make the following changes

@Configuration
@PropertySource(value = { "file:${catalina.home}/conf/my.properties" })
@Component
@MyAnnotation
public class MyAlert implements IAlert {
    @Autowired
    private Environment environment;
} 

I wanted to read properties located in conf folder of tomcat7, after making these changes my interceptor is unable to read my custom annotation @MyAnnotation . it says (custom message written in interceptor)

Annotation not present

and here is custom annotation

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

}

I really want the class should be intercepted and annotation must be detected on class if it is annotated. I also want to read properties from conf folder in that intercepted class.

Your check for the annotation fails because you are checking on the dynamic proxy's type instead of the actual annotated class's one. You can work around it like this:

pjp.getSignature().getDeclaringType().getAnnotation(RestController.class) != null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM