【问题标题】:AspectJ - How to log overriden method name instead of superclass method nameAspectJ - 如何记录重写的方法名称而不是超类方法名称
【发布时间】:2019-01-20 16:10:13
【问题描述】:

我为我的所有存储库、服务和控制器构建了一个记录器类。我正在使用以下方法记录每个方法调用:

@Before("execution(* com.mdenis.tno..controller..*(..)) || " + 
        "execution(* com.mdenis.tno..service..*(..)) || " + 
        "execution(* com.mdenis.tno..repository..*(..))")
private void logMethodCallWithParameters(JoinPoint joinPoint)
{
    String arguments = "";

    for (Object argument : Arrays.asList(joinPoint.getArgs()))
    {
        arguments = arguments + argument.toString() + ", ";
    }

    if (arguments.contains(", "))
    {
        arguments = arguments.substring(0, arguments.lastIndexOf(","));
    }

    if (arguments.compareTo("") == 0)
    {
        logger.debug("Method " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() 
            + " called with no argument");
    }
    else
    {
        logger.debug("Method " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() 
            + " called with argument(s) " + arguments);
    }
}

这很好用,但我的服务都扩展了一个包含常用方法的基础服务。因此,调用 PostServiceImpl 中的方法会导致以下日志语句:

Method com.mdenis.tno.service.impl.BaseServiceImpl.findAllPaginated returning with result Page 1 of 2 containing com.mdenis.tno.model.Post instances.

我想知道是否有办法记录扩展类名 (PostServiceImpl) 而不是超类名 (BaseServiceImpl)。

谢谢!

【问题讨论】:

    标签: java spring-boot aspectj pointcut


    【解决方案1】:

    你使用

    joinPoint.getTarget().getClass().getCanonicalName()
    

    类名。

    【讨论】:

    • 我认为您的意思是 getTarget().getClass().getCanonicalName() 是的,确实有效,谢谢!
    • 但是 JpaRepository 方法有一个副作用,它们返回类似“com.sun.proxy.$Proxy198.save”的方法名称。考虑到整个 Spring 代理的事情,我完全明白为什么会发生这种情况,但是有没有办法解决这个问题?
    • @Martin 不是我所知道的优雅的人。我不会将方面应用于存储库(而不是调用服务),但除此之外,您可能需要获取类的声明接口并记录最具体的接口,该接口扩展了激活方面的接口。
    • 也许您想查看我的answer here 并查看我的实用方法unProxy(..)。如果您将它集成到您​​的方面并像unProxy(joinPoint.getTarget()).getClass().getCanonicalName() 一样称呼它,它会有所帮助吗?我没有尝试,因为你没有分享 MCVE 我可以使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    相关资源
    最近更新 更多