package com.elab.spring.intercept.annotation;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ReflectiveMethodInvocation;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 实现缓存的拦截器
 *
 * @author ： liukx
 * @time ： 2020/7/9 - 20:08
 */
public class AnnotationInterceptor implements MethodInterceptor, Serializable {

    @Autowired(required = false)
    private List<AnnotationProcessService> cacheProcessServices;

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Object proceed = null;
        if (cacheProcessServices != null && invocation instanceof ReflectiveMethodInvocation) {
            ReflectiveMethodInvocation methodInvocation = (ReflectiveMethodInvocation)invocation;
            Method method = invocation.getMethod();
            Annotation[] annotations = method.getAnnotations();
            for (int i = 0; i < annotations.length; i++) {
                Annotation annotation = annotations[i];
                for (int j = 0; j < cacheProcessServices.size(); j++) {
                    AnnotationProcessService cache = cacheProcessServices.get(i);
                    if (annotation.annotationType() == cache.annotation()) {
                        proceed = cache.invokeWithinTransaction(methodInvocation);
                    }
                }
            }
            return proceed;
        }
        return invocation.proceed();
    }
}
