简体   繁体   English

无法在Spring AOP中检测类级自定义注释

[英]Unable to detect class level custom annotation in Spring AOP

I am trying to intercept classes in Spring with following settings 我试图通过以下设置拦截Spring中的类

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 . 我想读取位于tomcat7的conf文件夹中的属性,在进行这些更改后,我的拦截器无法读取我的自定义注释@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. 我还想在截取的类中读取conf文件夹中的属性。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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