我正在开发一个本应在本月晚些时候部署的Spring Boot API。我们为存储库创建了自己的接口,并扩展了CrudRepository。 Spring boot自动装配一切。
我想要做的是添加更多日志记录功能,例如LOGGER.info("searched for solution ID")
。
目前我们的代码如下:
@Repository
public interface ProductSolutionRepository extends CrudRepository<ProductSolution, String> {
public List<ProductSolution> findBySolutionId(@Param("solutionId") int solutionId);
由于Spring配置了所有内容,并没有真正看到一种装饰这些功能的方法来添加日志记录功能。有人可以通过向我指出文档,展示一个很好的例子,或解释日志装饰器背后的概念来帮助我吗?
答案 0 :(得分:3)
您可以使用AspectJ
使用RepositoryLoggingAspect
切换存储库接口层并记录方法名称,输入参数和输出。
为此目的假设@Aspect
类,您必须先使用import org.aspectj.lang.annotation.Aspect;
@Aspect
public class RepositoryLoggingAspect {
//..
}
对其进行注释:
@Pointcut("within(package.of.my.repositories..*)")
public void repositoriesPackagePointcut() {}
然后创建一个针对你想要剪切的存储库包的Pointcut:
@Around
最后用@Around("repositoriesPackagePointcut()")
public Object logMyRepos(ProceedingJoinPoint joinPoint) throws Throwable {
//log method name using: joinPoint.getSignature().getName()
//log method arguments using: Arrays.toString(joinPoint.getArgs())
//store and log method output using: Object myResult = joinPoint.proceed();
}
带注释的方法定义记录逻辑:
php.ini
答案 1 :(得分:2)
首先,我想为您指出一些冗余代码。
@Repository
注释存储库,spring boot可以自动对其进行自动装配。@Param
编写一个sql时,会使用@Query
,你只需要在这里声明你的参数。存储库是dao
层。通常的做法是,您应该为每个存储库创建一个service
,并将存储库自动装配到服务中。然后,您可以在那里实现事务或写日志。