gpt4 book ai didi

java - Spring JPA 数据与 REST 日志

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

我已经使用过这个教程Accessing JPA Data with REST创建一个简单的 RESTful Web 服务来访问数据库中的某些数据。效果很好。我喜欢它的简单性,并且我或多或少地了解它是如何工作的。

但是,我被要求添加一些自定义日志记录。每当 Web 服务被调用时,都会生成一个日志“Start - TIME”,并且在服务返回之前生成另一个日志“End - TIME”。有没有办法在不破坏我的包含 @Query 注释的方法的情况下做到这一点

public interface PersonRepository extends PagingAndSortingRepository<Person, Long>

我有点希望会有某种注释,但我似乎找不到任何东西。

有什么建议吗?

最佳答案

听起来像是 Spring-AOP 的一个例子!

very helpful tutorial 开始工作(还有 useful SO answer ),我在 TokenRepository 中执行任何方法之前和之后记录了一些内容

@Repository
public interface TokenRepository extends CrudRepository<Token, String> {
}

有趣的是

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingHandler {

Logger log = LoggerFactory.getLogger(this.getClass());

@Pointcut("this(org.springframework.data.repository.Repository)")
public void repository() { }

@Pointcut("execution(* *.*(..))")
protected void allMethod() { }

//before -> Any resource annotated with @Repository annotation
//and all method and function
@Before("repository() && allMethod()")
public void logBefore(JoinPoint joinPoint) {
log.info("Entering in Method : " +
joinPoint.getSignature().getName() + " at " + System.currentTimeMillis());
}

//After -> All method within resource annotated with @Repository annotation
@AfterReturning(pointcut = "repository() && allMethod()")
public void logAfter(JoinPoint joinPoint) {
log.info("Method Returned at : " + System.currentTimeMillis());
}
}

关于java - Spring JPA 数据与 REST 日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45443508/

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