我正在尝试使用以下设置拦截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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句