Spring AOP 進行統一的異常處理和日誌記錄

步驟

1.使用@Aspect註解標註一個java類,Spring將自動識別該類做爲切面Bean。java

@Aspect
public class ExceptionAndLogAspect {

}

2.在Spring配置文件中添加這個切面Bean,並啓動@AspectJ支持。apache

<!-- 配置切面的類 -->
<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.如今能夠寫個類作測試了。this

相關文章
相關標籤/搜索