我想将所有存储库调用包装在我的服务中,并使用 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
}
}
但似乎方面方法从未运行。我错过了什么?
最佳答案
假设您的 JpaRepository
类注释如下
@Repository
public interface JpaEmployeeRepository extends CrudRepository<JpaEmployee, Long> {
...
}
以下方面将拦截该类发生的所有方法调用
@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();
}
}
请注意,配置类最好留给配置条目,您可以为 Aspect 创建一个单独的类,并使用示例中给出的 @Component
对其进行注释。
确保您有@ComponentScan
来自动检测配置类上的Aspect和@EnableAspectJAutoProxy
。内容如下
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackageClasses= {RepositoryAspect.class})
public class AppConfig {
...
}
更新
以下是您的代码未按预期工作的原因
1.
@annotation: Limits matching to join points where the subject of the join point (the method being executed in Spring AOP) has the given annotation.
在这种情况下,方法没有被注释。
2.
配置类RepositoryMetrics
未使用@EnableAspectJAutoProxy进行注释。我假设 Spring AOP 没有在任何配置类中启用。
关于java - 如何使用周围方面包装所有存储库调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59635221/