gpt4 book ai didi

java - Spring AOP。如何为带注释的类中的所有公共(public)方法创建切入点

转载 作者:行者123 更新时间:2023-12-01 17:58:13 26 4
gpt4 key购买 nike

我需要处理从带有某些注释的类的公共(public)方法引发的所有异常。我尝试使用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 注释进行注释的类中的所有公共(public)方法?

最佳答案

您可以像这样创建方面,其中 @LogMe 是注释: @Pointcut("execution(@LogMe * *(..))") 匹配所有公共(public)方法。

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());
}
}

关于java - Spring AOP。如何为带注释的类中的所有公共(public)方法创建切入点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42993880/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com