Spring AOP:@annotation() 切入点与类型注释不匹配
Spring AOP: @annotation() pointcut does not match type annotation
我正在编写一个方面来记录控制器中每个 API 调用的请求和响应。
我希望能够在 class 上使用此注释,因此使用了 @Target(ElementType.TYPE)
之前我添加了 @Target(ElementType.Method) 并且我在方法上使用了这个注释并且它工作正常。
现在我想把它改成@Target(ElementType.TYPE)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ReLogger {}
@Aspect
@Component
public class ReLoggerAspect {
public static final Logger log = LoggerFactory.getLogger("ReLoggerAspect");
@PostConstruct
private void postConstruct() {
log.info("ReLoggerAspect Created");
}
@Around("@annotation(ReLogger)")
private Object reqLoggingAspect(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("Request {}",jointPoint.getArgs()[0);
}
}
在 class
上使用 @ReLoggerAspect
@RestController
@RequestMapping(value = "....", produces = { "application/json" })
@ReLogger
public class Samplecontroller {
/** Some logic here**/.....
}
调用 API SampleController 时不打印请求
您认为 @annotation
会匹配类型注释的前提是错误的,请参阅 (Spring AOP 手册](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop-pointcuts-designators):
@within
: Limits matching to join points within types that have the given annotation (the execution of methods declared in types with the given annotation when using Spring AOP).
@annotation
: Limits matching to join points where the subject of the join point (the method being executed in Spring AOP) has the given annotation.
因此,您应该使用 @within(fully.qualified.AnnotationType)
。
我正在编写一个方面来记录控制器中每个 API 调用的请求和响应。 我希望能够在 class 上使用此注释,因此使用了 @Target(ElementType.TYPE)
之前我添加了 @Target(ElementType.Method) 并且我在方法上使用了这个注释并且它工作正常。 现在我想把它改成@Target(ElementType.TYPE)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ReLogger {}
@Aspect
@Component
public class ReLoggerAspect {
public static final Logger log = LoggerFactory.getLogger("ReLoggerAspect");
@PostConstruct
private void postConstruct() {
log.info("ReLoggerAspect Created");
}
@Around("@annotation(ReLogger)")
private Object reqLoggingAspect(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("Request {}",jointPoint.getArgs()[0);
}
}
在 class
上使用 @ReLoggerAspect@RestController
@RequestMapping(value = "....", produces = { "application/json" })
@ReLogger
public class Samplecontroller {
/** Some logic here**/.....
}
调用 API SampleController 时不打印请求
您认为 @annotation
会匹配类型注释的前提是错误的,请参阅 (Spring AOP 手册](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop-pointcuts-designators):
@within
: Limits matching to join points within types that have the given annotation (the execution of methods declared in types with the given annotation when using Spring AOP).
@annotation
: Limits matching to join points where the subject of the join point (the method being executed in Spring AOP) has the given annotation.
因此,您应该使用 @within(fully.qualified.AnnotationType)
。