通过AOP 实现异常统一管理

package com.zhang.shine.cache;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class MethodLogAspectJ {

    @Pointcut("@annotation(com.zhang.shine.cache.MethodLog)")
    public void methodCachePointcut() {
    }

    @Around("methodCachePointcut()")
    public Object methodCacheHold(ProceedingJoinPoint joinPoint)
            throws Throwable {
        System.out.println("aop start ");
        String methodRemark = getMthodRemark(joinPoint);
        Object result = null;
        try {
            // 记录操作日志...谁..在什么时间..做了什么事情..
            result = joinPoint.proceed();
        } catch (Exception e) {
            // 异常处理记录日志..log.error(e);
            throw e;
        }

        System.out.print(methodRemark);
        System.out.println("aop end ");
        return result;
    }

    // 获取方法的中文备注____用于记录用户的操作日志描述
    public static String getMthodRemark(ProceedingJoinPoint joinPoint)
            throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();

        Class targetClass = Class.forName(targetName);
        Method[] method = targetClass.getMethods();
        String methode = "";
        for (Method m : method) {
            if (m.getName().equals(methodName)) {
                Class[] tmpCs = m.getParameterTypes();
                if (tmpCs.length == arguments.length) {
                    MethodLog methodCache = m.getAnnotation(MethodLog.class);
                    methode = methodCache.remark();
                    break;
                }
            }
        }
        return methode;
    }

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

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MethodLog {
    String remark() default "";
}


public class Sev {
    @MethodLog(remark="增加用户信息")
    public String addUser(int type,int parentid){
        return "";
    }
}
原文地址:https://www.cnblogs.com/zuiyirenjian/p/4034056.html