簡體   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