繁体   English   中英

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

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

我试图通过以下设置拦截Spring中的类

拦截器

@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();
    }   
}

被拦截的如下

@Component
@MyAnnotation
public class MyAlert implements IAlert {

}

除非我做出以下更改,否则每件事情都会正常工作

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

我想读取位于tomcat7的conf文件夹中的属性,在进行这些更改后,我的拦截器无法读取我的自定义注释@MyAnnotation 它说(用拦截器写的自定义消息)

注释不存在

这是自定义注释

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

}

我真的希望该类应该被截获,并且如果注释,必须在类上检测注释。 我还想在截取的类中读取conf文件夹中的属性。

检查注释失败是因为您正在检查动态代理的类型而不是实际注释类的类型。 你可以像这样解决它:

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

暂无
暂无

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

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