2017-08-15 52 views
1

我正在开发本应在本月晚些时候部署的Spring Boot API。我们为存储库创建了自己的接口,并扩展了CrudRepository。 Spring Boot autowires的一切。装饰弹簧启动存储库

我想要做的是添加更多日志功能,如LOGGER.info("searched for solution ID")

目前我们的代码看起来是这样的:

@Repository 
public interface ProductSolutionRepository extends CrudRepository<ProductSolution, String> { 

    public List<ProductSolution> findBySolutionId(@Param("solutionId") int solutionId); 

由于Spring配置一切真的没有看到装饰这些功能添加日志记录功能的一种方式。有人可以帮我指点一下文档,展示一个很好的例子,或者解释日志装饰器背后的概念吗?

+0

龙目岛或AOP也许? – Marged

+0

查看https://stackoverflow.com/questions/26258158/how-to-instrument-advice-a-spring-data-jpa-repository,你需要的是AOP –

回答

3

首先,我想指出一些冗余代码给你。

  • 您不需要使用@Repository注释存储库,spring boot可以自动自动装载它。
  • @Param当你用@Query写一个sql时,你只需要在这里声明你的参数。

存储库是dao层。通常的做法是,您应该为每个存储库创建一个service并将该存储库自动装入该服务。然后你可以在那里实现事务或写入日志。

2

您可以使用单个文件AOP Logging Aspect使用AspectJ切割您的存储库接口图层和日志记录方法名称,输入参数和输出。

假设用于此目的的RepositoryLoggingAspect类,你必须与@Aspect第一标注为:

import org.aspectj.lang.annotation.Aspect; 

@Aspect 
public class RepositoryLoggingAspect { 
//.. 
} 

,然后创建一个切入点瞄准你的资料库,包你想切翻过:

@Pointcut("within(package.of.my.repositories..*)") 
public void repositoriesPackagePointcut() {} 

最后在@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(); 
}