java - 无法检测 Spring AOP 中的类级别自定义注释

标签 java reflection tomcat7 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。它说(用拦截器编写的自定义消息)

Annotation not present

这里是自定义注释

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

}

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

最佳答案

您对注解的检查失败了,因为您检查的是动态代理的类型,而不是实际带注解类的类型。您可以像这样解决它:

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

关于java - 无法检测 Spring AOP 中的类级别自定义注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35057429/

相关文章:

java - 无法调用 persistence.xml 文件中的 JNDI 资源

java - Spring Batch 中连接过多异常

java序列化导致utfdataformaexception

java - 将特定时间分配给日历

c# - 从抽象类反射(reflect)实现的私有(private)方法?

c# - C# 中的显式构造函数调用

tomcat - 使用嵌入式 Tomcat 7 在 Spring Boot 中启用 SSL - FileNotFoundException 和 o.a.coyote.http11.Http11NioProtocol 问题

java - Hikari 池 activeConnections 未显示在 JMX mbean 中

java - 尝试每 x 秒执行一次文件

c# - MethodInfo.MetadataToken 的目的是什么