Spring AOP 进行统一的异常处理和日志记录

步骤

1.使用@Aspect注解标注一个java类,Spring将自动识别该类作为切面Bean。

@Aspect
public class ExceptionAndLogAspect {

}

2.在Spring配置文件中添加這個切面Bean,并启动@AspectJ支持。

<!-- 配置切面的类 -->
<bean id="ExceptionAndLogAspect" class="com.student.xl.util.ExceptionAndLogAspect"></bean>
<!--启动@AspectJ支持-->
<aop:aspectj-autoproxy/>

3.添加增强处理

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

/**
 * 统一处理异常和日志的切面类
 * @author louzi
 */
@Aspect
public class ExceptionAndLogAspect {
    Logger log = Logger.getLogger(this.getClass().getName());

    //Before增强:在目标方法被执行的时候织入增强
    //匹配com.student.xl包下面的所有类的所有方法的执行作为切入点
    @Before("execution(* com.student.xl.*.*.*(..))")
    public void beforeWave(JoinPoint joinPoint){
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        System.out.println("进入"+className+"类的"+methodName+"方法。");
    }
    
    //AfterReturning增强:在目标方法正常完成后被织入
    //rvt是目标方法的返回值
    @AfterReturning(returning="rvt",pointcut="execution(* com.student.xl.*.*.*(..))")
    public void afterWave(Object rvt){
        System.out.println("获得目标方法返回值:"+rvt);
    }
    
    //AfterThrowing增强:处理程序中未处理的异常
    //ex是目标方法拋出的异常
    @AfterThrowing(throwing="ex",pointcut="execution(* com.student.xl.*.*.*(..))")
    public void exceptionDispose(JoinPoint joinPoint,Throwable ex){
        String className = joinPoint.getTarget().getClass().getName(); //切入方法所属类名
        String methodName = joinPoint.getSignature().getName(); //切入的方法名 
        Object[] params = joinPoint.getArgs(); //目标方法传入的参数
        String param = "入参为:";
        
        if(params != null && params.length > 0){
            for(Object p : params){
                param += p + ",";
            }
            param = param.substring(0,param.lastIndexOf(","));
        }
        log.error("[Exception]:["+className+"]"+methodName+":" + ex);
        System.out.println("【"+className+"】:"+methodName+"执行时出现异常:"+ex+"。");
        System.out.println(param);
    }
}

4.现在可以写个类做测试了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值