使用spring aop拦截异常

使用spring aop拦截异常

一、引入相应的jar包

        
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjrtartifactId>
            <version>1.6.10version>
        dependency>
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.6.10version>
        dependency>
        <dependency>
            <groupId>cglibgroupId>
            <artifactId>cglib-nodepartifactId>
            <version>2.2version>
        dependency>
        

二、修改spring配置文件

添加如下配置

  <aop:aspectj-autoproxy />   
  <context:component-scan base-package="mfy"/>

三、定义切面类

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


@Component
@Aspect
public class ExceptionAspect {

    private static Logger LOG = LoggerFactory
            .getLogger(ExceptionAspect.class);

    @Pointcut("execution(* process.spring.exception.*Delegate.*(..))")
    public void pointCut() {
    }

    @AfterThrowing(pointcut = "pointCut()", throwing = "error")
    public void afterThrowing(JoinPoint jp, Throwable error) {
        LOG.error("ExceptionAspect error");
        if (null != jp.getArgs() && jp.getArgs().length > 0) {
            Object firstArg = jp.getArgs()[0];
            String errorStack = this.getExceptionStack(error);   
            LOG.error(errorStack);
            LOG.error(firstArg);
        }
    }

    private String getExceptionStack(Throwable error) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        PrintStream ps = new PrintStream(baos);  
        error.printStackTrace(ps);  
        String errorStack = baos.toString();  
        ps.close();
        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return errorStack;
    }

}

最后,运行抛出异常的类即可打印出切面类中的异常。

你可能感兴趣的:(spring)