繁体   English   中英

春季AOP。 如何在带注释的类中为所有公共方法设置切入点

[英]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件事情之一:

  1. @Component放在@Aspect旁边
  2. @Aspect定义为@Bean
  3. 添加一个额外的`@ComponentScan(includeFilter = {@ Filter(org.aspectj.lang.annotation.Aspect)}}

显然,选项1是最容易做到的。

首先,我尝试注释一些引发异常的方法。 它工作正常,但是如何使所有使用@Loggable注释的类中的公共方法都可以使用此方法呢?

您需要编写一个与之匹配的切入点。 像下面这样的东西应该可以解决问题。

@Pointcut("public * ((@Loggable *)+).*(..)) && within(@Loggable *)")

和...一起

@Pointcut("@Loggable * *(..)")

这将在带注释的类中使用带注释的方法或公共方法。 这是受Spring框架AnnotationTransactionAspect代码的启发。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM