Java – class level custom annotations cannot be detected in spring AOP

I tried to intercept classes in spring with the following settings

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

The intercepted classes are as follows

@Component
@MyAnnotation
public class MyAlert implements IAlert {

}

Everything will work 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 want to read the properties in the conf folder of tomcat7. After making these changes, my interceptor cannot read my custom comment @ myannotation It says (custom messages written with interceptors)

This is a custom comment

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

}

I really hope that this class should be intercepted, and if comments, comments must be detected on the class I also want to read the properties in the conf folder in the intercepted class

Solution

The annotation check failed because you are checking the type of the dynamic proxy instead of the actual annotation class You can solve it like this:

pjp.getSignature().getDeclaringType().getAnnotation(RestController.class) != null
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>