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

时间:2019-01-19 10:42:52

标签: spring-boot spring-data-jpa aspectj spring-aop

我试图在使用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:naresh@xyz.com
Class******com.xyz.security.service.impl.UserServiceImpl
Method******forgotPassword
parameterNames******userEmail:naresh@xyz.com
Class******com.sun.proxy.$Proxy436
Method******findByUserEmail

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

1 个答案:

答案 0 :(得分:1)

这是我所做的事的一个例子。

通过添加+符号,还将拦截实现我的存储库或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