spring aop 一個擋板例子

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 定義一個擋板
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface BaffleAn {

}

 

 

import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;


/**
 * 擋板切面類
 */
@EnableAspectJAutoProxy
@Component
@Aspect
public class BaffleAnAspect {

    @Pointcut("@annotation(BaffleAn)")
    public void point() {}
    
    @Around("point()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        return BaffleAnService.handler(point);
    }
    
    public static Map<String,Object> getFieldsNameValueMap(JoinPoint joinPoint) throws Exception {   
        Object[] args = joinPoint.getArgs();
        String classType = joinPoint.getTarget().getClass().getName();    
        Class<?> clazz = Class.forName(classType);    
        String clazzName = clazz.getName();    
        String methodName = joinPoint.getSignature().getName(); //獲取方法名稱   
        Map<String,Object > map=new HashMap<String,Object>();  
        ClassPool pool = ClassPool.getDefault();    
        ClassClassPath classPath = new ClassClassPath(BaffleAnAspect.class);    
        pool.insertClassPath(classPath);    
        CtClass cc = pool.get(clazzName);    
        CtMethod cm = cc.getDeclaredMethod(methodName);    
        MethodInfo methodInfo = cm.getMethodInfo();  
        CodeAttribute codeAttribute = methodInfo.getCodeAttribute();    
        LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);    
        if (attr == null) {    
            throw new RuntimeException();
        }    
        int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;    
        for (int i = 0; i < cm.getParameterTypes().length; i++){    
            map.put( attr.variableName(i + pos),args[i]);//paramNames即參數名    
        }    
        return map;    
    }    
}

 

import java.util.Map;

import org.aspectj.lang.ProceedingJoinPoint;

/**
 * 
    擋板處理類
 */
public class BaffleAnService {

    public static Object handler(ProceedingJoinPoint point) throws Throwable {
        Object obj=null;
        Map<String,Object> map=BaffleAnAspect.getFieldsNameValueMap(point);
        if(map == null) {
            obj=point.proceed();
            return obj;
        }
        if(map.containsKey("AA")) {
            //擋板業務處理
        }
        obj=point.proceed();
        return obj;
        
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章