在Spring Boot Aspect中没有获得实际的参数名称

问题描述 投票:0回答:1

我试图在使用Aspectj动态执行每个方法之前添加日志语句。

码:

@Component
@Aspect
public class MethodLogger {
    DiagnosticLogger logger = DiagnosticLogger.getLogger(getClass());

    @Before("execution(* com.xyz..*.*(..))")
    public void beforeMethod(JoinPoint joinPoint) throws Throwable {
        System.out.println("Class******" + joinPoint.getTarget().getClass().getName());
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        System.out.println("Method******" + signature.getName());

        // append args
        Object[] args = joinPoint.getArgs();

        String[] parameterNames = signature.getParameterNames();
        if (parameterNames != null) {
            for (int i = 0; i < parameterNames.length; i++) {
                System.out.println("parameterNames******" + parameterNames[i] + ":" + args[i]);
            }
        }
    }

}

输出:

Class******com.xyz.security.web.UserController
Method******forgotPassword
parameterNames******userEmail:[email protected]
Class******com.xyz.security.service.impl.UserServiceImpl
Method******forgotPassword
parameterNames******userEmail:[email protected]
Class******com.sun.proxy.$Proxy436
Method******findByUserEmail

我能够获得控制器和服务级别。但是当涉及Spring Data JPA Repository方法时它无法打印。如何在存储库级别获取参数名称?

spring-boot spring-data-jpa aspectj spring-aop
1个回答
1
投票

这是我做的一个例子。

通过添加+符号,也可以拦截实现我的Repository或com.example。**中任何其他接口的类。

@Slf4j
@Component
@Aspect
public class MethodLogger {

    @Before("execution(* com.example.*..*+.*(..))")
    public void beforeMethod(JoinPoint joinPoint) throws Throwable {
        log.info("Class******" + joinPoint.getTarget().getClass().getName());

        for (Class<?> theinterface: joinPoint.getTarget().getClass().getInterfaces()) {
            log.info("Interfaces******" + theinterface.getName());
        }

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        log.info("Method******" + signature.getName());

        Object[] args = joinPoint.getArgs();

        String[] parameterNames = signature.getParameterNames();
        if (parameterNames != null) {
            for (int i = 0; i < parameterNames.length; i++) {
                log.info("parameterNames******" + parameterNames[i] + ":" + args[i]);
            }
        }
    }

}

参数名称也会被记录:

Class******com.sun.proxy.$Proxy87
Interfaces******com.example.demoaspectmethodlogging.control.EmployeeRepository
Interfaces******org.springframework.data.repository.Repository
Interfaces******org.springframework.transaction.interceptor.TransactionalProxy
Interfaces******org.springframework.aop.framework.Advised
Interfaces******org.springframework.core.DecoratingProxy
Method******findByName
parameterNames******name:Simon
© www.soinside.com 2019 - 2024. All rights reserved.