[我想将服务中的所有存储库调用都包装在“环绕”方面,以创建一些指标。
我的所有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> { ... }
以下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
来自动检测Configuration类上的Aspect和@EnableAspectJAutoProxy
。如下所示
@Configuration @EnableAspectJAutoProxy @ComponentScan(basePackageClasses= {RepositoryAspect.class}) public class AppConfig { ... }
更新
以下是原因,您的代码无法正常工作
1。
[Pointcut designator @annotation
@@ notation:将匹配项限制为连接点(Spring AOP中正在执行的方法
)具有给定的注释。在这种情况下,方法未注释。
2。
配置类RepositoryMetrics
未被注释为@EnableAspectJAutoProxy。我认为在任何Configuration类中都未启用Spring AOP。