gpt4 book ai didi

java - 使用方面进行日志记录

转载 作者:行者123 更新时间:2023-12-02 07:29:09 25 4
gpt4 key购买 nike

拥有一个包含 Facade 层、Service 层和 Dao 层的 RESTful Web 服务。尝试记录类的所有方法的所有调用,并用注释 @Log 标记

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
}

这是方面代码:

public class LoggingAspect {
@Around("@target(Log)")
public Object log(ProceedingJoinPoint pjp) throws Throwable {
log.debug("Start " + pjp.getSignature().getName());
Object result = pjp.proceed();
log.debug("End " + pjp.getSignature().getName());
return result;
}
}

Facade、Service 和 Dao 均用 @Log 标记。一些例子:

public Obj Facade.createObj(String name){ //1
return service.createObj(name);
}

public Obj Service.createObj(String name){ //2
return dao.createObj(name);
}

public Obj Dao.createObj(String name){ //3
Long idOfCreatedObj = /*code that creates an object and returns it's ID*/;
return loadObjById(idOfCreatedObj); /* load the created object by id */
}

public Obj Dao.loadObjById(Long id){ //4
return /* code that loads the object by it's id */;
}

在此示例中,方法 1、2、3 已成功记录。但嵌套的 dao 方法(loadObjById)未记录。

为什么?

附注在 spring-config.xml 中有 <aop:aspectj-autoproxy proxy-target-class="true"/>

最佳答案

问题是 self 调用(this.methodcall())绕过了 Spring 创建的用于处理横切问题的动态/cglib 代理。

修复方法是使用完整的 Aspectj(编译时或加载时编织)或通过获取代理进行调用(而不是使用 this.methodCall(),而是使用 proxy.methodCall()

您可以通过以下方式获取代理:

<aop:aspectj-autoproxy expose-proxy="true"/>

在您的代码中:AopContext.currentProxy()将为您提供对代理的引用。如果您有兴趣,这里有一篇关于此的博客文章 - http://www.java-allandsundry.com/2012/07/reference-to-dynamic-proxy-in-proxied.html

关于java - 使用方面进行日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13157225/

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