gpt4 book ai didi

java - 如何使用spring aop记录@RequestMapping注解的方法的成本时间?

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:52 25 4
gpt4 key购买 nike

我想记录所有用@RequestMapping注释的方法的成本时间。但是下面的代码不起作用。

@Component
@Aspect
@Slf4j
public class LogAop {
@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
public void req() {}

@Before("req()")
public void logMethod(JoinPoint jp) {
String methodName = jp.getSignature().getName();
}


@Around("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
public Object doAroundController(ProceedingJoinPoint pjp) throws Throwable {
long begin = System.currentTimeMillis();
log.info(" method {} begin",
pjp.getSignature().getName());

Object o;

try {
o = pjp.proceed();
} catch (Throwable e) {
throw e;
} finally {
long costTime = System.currentTimeMillis() - begin;
log.info(" method {} ended cost time {}ms",
pjp.getSignature().getName(), costTime);
}

return o;
}

}

doAroundControllerlogMethods 都不起作用。

如果我将上面的代码更改为下面的代码,那就可以了:

@Pointcut("execution(public * *(..))")
public void publicMethod() {}




@Around("publicMethod()")
public Object doAroundController(ProceedingJoinPoint pjp) throws Throwable {

在 applicationContext.xml 中,我使用以下行启用 spring aop:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
default-autowire="byType" default-lazy-init="true">
...
<aop:aspectj-autoproxy/>

使用 JDK 7、Spring MVC 2.5.6、AspectJ 1.7.2。

最佳答案

我有类似的东西并且它有效(最重要的变化:within而不是annotation)。我现在不确定,但我想我想实现相同的功能,但不能那样做,所以我在 Controller 中的每个方法上添加了方面,因为无论如何它们都用 @RequestMapping 注释(或者至少应该是)。

@Pointcut("@within(org.springframework.web.bind.annotation.RestController)")
void restController() {}

@Pointcut("execution(public * *(..))")
void publicMethod() {}

@Before("restController() && publicMethod()")
void myMethod(JoinPoint joinPoint) {
...
}

关于java - 如何使用spring aop记录@RequestMapping注解的方法的成本时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53652003/

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