我正在编写一个方面来记录控制器中每个API调用的请求和响应。 我希望能够在类上使用此批注,因此使用了@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);
}
}
在类上使用@ReLoggerAspect
@RestController
@RequestMapping(value = "....", produces = { "application/json" })
@ReLogger
public class Samplecontroller {
/** Some logic here**/.....
}
当调用API SampleController时,它不会打印请求
答案 0 :(得分:1)
您假设@annotation
将与类型注释匹配的前提是错误的,请参阅(Spring AOP手册](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop-pointcuts-designators):
@within
:将匹配限制为具有给定注释的类型内的连接点(使用Spring AOP时,使用给定注释的类型中声明的方法的执行)。
@annotation
:将匹配点限制为连接点的主题(在Spring AOP中执行的方法)具有给定注释的连接点。
因此,您应该使用@within(fully.qualified.AnnotationType)
。