有什么方法可以使用Spring AOP获取查询字符串吗?

时间:2019-04-30 11:35:41

标签: java spring hibernate spring-data-jpa aop

使用Spring AOP,我正在获取有关CrudRepository方法的一些数据(方法名称,参数,经过的时间)。但是我还需要将查询字符串添加到这些数据中。

我一直在研究尝试使用Spring AOP拦截其他方法。我什至看到p6spy还有替代方法。或可以将日志配置为显示日志,但是我认为这不是更好的解决方案。

这是我要从中获取信息的电话的示例:

package com.test.example.server.persistence.mapping.api;

import org.springframework.data.repository.CrudRepository;
import com.test.example.server.model.mapping.Opponent;

public interface OpponentRepository extends CrudRepository<Opponent, Long> {
    Opponent findByUserId(Long userId);
}

在这里,我正在使用Spring AOP拦截这些调用,并获取一些信息。我还需要获取执行的查询字符串。

package com.test.example.persistence.logging;
@Aspect
@Component
public class Logging {

private static final String POINTCUT =
        "execution(* com.test.example.server.persistence.mapping.api..*(..)) ";

@Pointcut(POINTCUT)
public void dataAccessMethods() {
}

@Around("dataAccessMethods()")
public Object profile(ProceedingJoinPoint pjp) throws Throwable {
    long start = System.currentTimeMillis();
    Object output = pjp.proceed();
    long elapsedTime = System.currentTimeMillis() - start;
    StringBuilder args = new StringBuilder("[");
    for (Object arg : pjp.getArgs()) {
        args.append(arg);
    }
    args.append("]");

    System.out.println(pjp.getSignature().getName() + "," + args + "," + elapsedTime + "," + LocalDateTime.now());
    //Here I would need to get the query string, and concatenate it to the previous string.
    //Later it will be modified to store this instead of printing it by console (The System.out is used only to test it).

    return output;
}
...

输出是:

    findByUserId,[4],25,2019-04-29T12:31:55.565

但是预期的输出是:

    findByUserId,[4],25,"Select * from opponent where userId = 4",2019-04-29T12:31:55.565

0 个答案:

没有答案