加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 02:12:40 所属栏目:Java 来源:网络整理
导读:我试图通过以下设置拦截 Spring中的类 拦截器 @Aspect@Componentpublic class MyInterceptor { @Around("execution(* com.example.services..*(..))") public Object intercept(ProceedingJoinPoint pjp) throws Throwable { if (pjp.getTarget() != null pj
我试图通过以下设置拦截 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读