Spring Aspect递归调用

时间:2014-04-17 15:44:53

标签: spring-aop aspect

我必须创建方面,应该在抛出自定义异常之后再次调用具有相同参数的方法,其中抛出此异常,但方法递归调用必须不多于5次。是否有可能这样做?

1 个答案:

答案 0 :(得分:0)

我使用的注释更流畅:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
/** Annotation for ascect using to define how many times try running     annotated method */

public @interface TryMultiplyTimes {
    /** define how many time try running method */
    int times() default 0;
}

在你想要的方法上尝试多次运行获取注释,并声明你需要多少次(在我的例子中是DAO类):

@Component
public class CustomerDAOImpl{

@TryMultiplyTimes(times=5)
public void addCustomerThrowException(String text) throws Exception {
    System.out.println("addCustomerThrowException() is running with args: "+text);
    throw new Exception("Generic Error");
}

最重要的部分:方面。我的方面基于注释围绕尝试调用方法。 Aspect尝试调用方法,当获取异常时,检查是否可以多次调用方法;如果不是,那就是例外。 Key是calss和方法的hashCode,用于区分由不同实体调用这个相同的方法。

@Aspect
public class MultiTimesAspect {

@Around("@annotation(multiTimeAnnotation)")
public void aspectMultiTime(ProceedingJoinPoint joinPoint, TryMultiplyTimes multiTimeAnnotation)throws Throwable {

    System.out.println("***********************************************");
    System.out.println("before running method: "+ joinPoint.getSignature().getName());

    try {
        joinPoint.proceed(joinPoint.getArgs()); //running method with it's args
    } catch (Throwable e) {
        //if method throws exception:
        int times = multiTimeAnnotation.times();//get how many times can trying
        String key = createKey(joinPoint);      //create key (class hashCode and method hashCode) for managing map 
        if (repeatsMap.get(key) == null) {
            repeatsMap.put(key, 1);             //if method called first time
        }

        int proceeded = repeatsMap.get(key);
        if (proceeded < times) {
            //if can try more times preincrement reapeats and recursively call aspect
            repeatsMap.replace(key, ++proceeded);
            aspectMultiTime(joinPoint, multiTimeAnnotation);
        } else {
            //if can't call method anymore, delete from map key and throws excetion
            repeatsMap.remove(key);
            throw e;
        }

    }

    System.out.println("after running method: " + joinPoint.getSignature().getName());
    System.out.println("***********************************************");
}

private String createKey(JoinPoint joinPoint) {
    StringBuffer buffer = new StringBuffer();
    buffer.append(joinPoint.getTarget().toString()).append(".")
            .append(joinPoint.getThis().toString());
    return buffer.toString();
}
}

测试课

public class Test {

public static void main(String... args){
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
            "spring-aop.xml");
    CustomerDAOImpl customer= (CustomerDAOImpl) ctx.getBean("customerBo");
    try {
        customer.addCustomerThrowException("**TEST**");
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}