我正在尝试使用以下设置在 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/