【问题标题】:How to wrap all repository calls with an Around aspect如何使用 Around 方面包装所有存储库调用
【发布时间】:2020-01-07 19:52:25
【问题描述】:

我想将我的服务中的所有存储库调用都包含在 Around 方面,以创建一些指标。

我所有的JpaRepositories 都用org.springframework.stereotype.Repository 注释,所以我尝试了这样的事情:

@Configuration
@Aspect
public class RepositoryMetrics {

    @Around("@annotation(org.springframework.stereotype.Repository)")
    public void logQueryTime(ProceedingJoinPoint joinPoint) throws Throwable {
        //Some logic here
        joinPoint.proceed();
        //Some logic here
    }
}

但似乎方面方法永远不会运行。我错过了什么?

【问题讨论】:

    标签: java spring-data aop spring-aop


    【解决方案1】:

    假设您的 JpaRepository 类注释如下

    @Repository
    public interface JpaEmployeeRepository extends CrudRepository<JpaEmployee, Long> {
    ...
    }
    

    Following Aspect 会拦截该类发生的所有方法调用

    @Component
    @Aspect
    public class RepositoryAspect {
    
        @Pointcut("@within(org.springframework.stereotype.Repository)")
        public void repositoryAnnotationPointCut() {}
    
        @Around("repositoryAnnotationPointCut()")
        public void logQueryTime(ProceedingJoinPoint pjp) throws Throwable {
    
            System.out.println("logged for "+pjp.toLongString());
            pjp.proceed();
        }
    }
    

    请注意,最好将 Configuration 类留给配置条目,您可以为 Aspect 创建一个单独的类,并使用 @Component 对其进行注释,如示例中所示。

    确保您有 @ComponentScan 自动检测配置类上的 Aspect 和 @EnableAspectJAutoProxy。如下

    @Configuration
    @EnableAspectJAutoProxy
    @ComponentScan(basePackageClasses= {RepositoryAspect.class})
    public class AppConfig {
    ...
    }
    

    更新

    以下是原因,您的代码没有按预期工作

    1.

    Pointcut designator@注释

    @annotation:将匹配限制为连接点 连接点(Spring AOP 中正在执行的方法)具有给定的 注释。

    在这种情况下,方法没有注释。

    2.

    配置类 RepositoryMetrics 未使用 @EnableAspectJAutoProxy 进行注释。我假设在任何配置类中都没有启用 Spring AOP。

    【讨论】:

      猜你喜欢
      • 2019-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 2023-03-16
      • 2018-04-06
      相关资源
      最近更新 更多