![](/img/trans.png)
[英]Spring AOP pointcut for all public methods of an annotatted class (including parent class methods)
[英]Spring AOP. How to make pointcut for all public methods in annotated class
我需要处理从带有某些注释的类的公共方法引发的所有异常。 我试图使用Spring AOP。 这是我的记录器:
@Aspect
public class Logger {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Pointcut("@annotation(loggable)")
public void isLoggable(Loggable loggable) {
}
@AfterThrowing(pointcut = "isLoggable(loggable)", throwing = "e")
public void afterThrowing(Loggable loggable, Exception e) throws Throwable {
log.error("AFTER", e);
}
@Loggable
是我的注释。
然后,我将@EnableAspectJAutoProxy
批注添加到我的配置类中。
首先,我尝试注释一些引发异常的方法。 它工作正常,但是如何使所有使用@Loggable
注释的类中的公共方法都可以使用此方法呢?
您可以创建这样的方面,其中@LogMe
是注释: @Pointcut("execution(@LogMe * *(..))")
以匹配所有公共方法。
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
@Aspect
@Component
public class LogExecutionTime {
private static final String LOG_MESSAGE_FORMAT = "%s.%s execution time: %dms";
private static final Logger logger = LoggerFactory.getLogger(LogExecutionTime.class);
@Pointcut("execution(@LogMe * *(..))")
public void isAnnotated() {}
/**
* Method will add log statement of running time of the methods which are annotated with @LogMe
* @param joinPoint
* @return
* @throws Throwable
*/
@Around("isAnnotated()")
public Object logTimeMethod(ProceedingJoinPoint joinPoint) throws Throwable {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Object retVal = joinPoint.proceed();
stopWatch.stop();
logExecutionTime(joinPoint, stopWatch);
return retVal;
}
private void logExecutionTime(ProceedingJoinPoint joinPoint, StopWatch stopWatch) {
String logMessage = String.format(LOG_MESSAGE_FORMAT, joinPoint.getTarget().getClass().getName(), joinPoint.getSignature().getName(), stopWatch.getTotalTimeMillis());
logger.info(logMessage.toString());
}
}
用@Aspect
注释的类不是@Component
因此如果启用了组件扫描,则不会选中该类。 如果您的上下文中没有Aspect,则AOP没有任何用处。
要解决此问题,您可以做3件事情之一:
@Component
放在@Aspect
旁边 @Aspect
定义为@Bean
显然,选项1是最容易做到的。
首先,我尝试注释一些引发异常的方法。 它工作正常,但是如何使所有使用@Loggable注释的类中的公共方法都可以使用此方法呢?
您需要编写一个与之匹配的切入点。 像下面这样的东西应该可以解决问题。
@Pointcut("public * ((@Loggable *)+).*(..)) && within(@Loggable *)")
和...一起
@Pointcut("@Loggable * *(..)")
这将在带注释的类中使用带注释的方法或公共方法。 这是受Spring框架AnnotationTransactionAspect
代码的启发。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.