Spring 从连接点获取方法引用
我需要在SpringAOP@afterhrough内多次重试以执行相同的方法。是否有任何方法可以使用JoinPoint引用执行它?如果不是,最好的方法是什么。我需要在不使用spring重试的情况下,通过在目标方法中注释来知道答案Spring 从连接点获取方法引用,spring,spring-aop,Spring,Spring Aop,我需要在SpringAOP@afterhrough内多次重试以执行相同的方法。是否有任何方法可以使用JoinPoint引用执行它?如果不是,最好的方法是什么。我需要在不使用spring重试的情况下,通过在目标方法中注释来知道答案 @Pointcut("@annotation(DBRecoverable)") public void repositoryClassMethods() {} @AfterThrowing(value = "repositoryClassMethods()", thr
@Pointcut("@annotation(DBRecoverable)")
public void repositoryClassMethods() {}
@AfterThrowing(value = "repositoryClassMethods()", throwing = "ex")
public void logExecutionTime(JoinPoint joinPoint, RuntimeException ex) throws Throwable {
//Re-execute the method again
}
我不知道是否可以使用@AfterThrowing切入点,但您可以像这样使用@Around切入点 例如:
@Around("repositoryClassMethods()")
public Object invoke(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
RuntimeException runtimeException = null;
for (int i = 0; i < MAX_TRIES; i++) {
try {
return proceedingJoinPoint.proceed();
}
catch (RuntimeException e) {
runtimeException = e;
}
}
throw runtimeException;
}
您可能需要通过以下方式获取目标方法:
public void filter(JoinPoint point) {
Object[] args = point.getArgs();
Class<?>[] argTypes = new Class[point.getArgs().length];
for (int i = 0; i < args.length; i++) {
argTypes[i] = args[i].getClass();
}
Method method;
try {
method = point.getTarget().getClass().getMethod(point.getSignature().getName(), argTypes);
} catch (NoSuchMethodException | SecurityException e) {
throw new RuntimeException(e);
}
if (method != null)
// do with the method ref
}
没有回答你的问题,我只是想让您注意spring retry库,它可能会实现您想要手动实现的功能:我的要求是创建一个注释,在我的存储库类中使用它,并在一个方法中处理@Recover,而不是添加我想要修改的所有方法,因为Gustavo说他不确定:@Afterhrowing是这肯定是错误的建议指示器,只有在这里使用@Around,你才能这样做。在@After或@AfterThrowing中,您无法更改控制流,只能在方法已结束或引发异常后触发其他操作。另请参见我的答案和。阅读SpringAOP手册也会有所帮助。我在使用@Around时遇到的问题是,在我的例子中,实际的异常将从@Transactional注释中抛出。虽然如果对带有@Transactional注释的方法使用@Around,此方法不会引发任何与事务创建相关的异常