用spring的AOP实现异常拦截
Spring支持四种拦截类型:目标方法调用前(before),目标方法调用后(after),目标方法调用前后(around),以及目标方法抛出异常(throw)。
最近用到spring的AOP来实现异常拦截,用到了spring的ThrowsAdvice。ThrowsAdvice是一个标示接口,我们可以在类中定义一个或多个,来捕获定义异常通知的bean抛出的异常,并在抛出异常前执行相应的方法。
import org.springframework.aop.ThrowsAdvice;
import org.springframework.aop.framework.ProxyFactory;
import java.lang.reflect.Method;
/**
* Copyright 2007 GuangZhou Cotel Co. Ltd.
* All right reserved.
* 异常拦截类.
* @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a>
* @version 1.0
* Creation date: 2007-7-24 - 下午08:12:25
*/
public class ExceptionAdvisor implements ThrowsAdvice {
public static void main(String[] args) {
TestBean bean = new TestBean();
ProxyFactory pf = new ProxyFactory();
pf.setTarget(bean);
pf.addAdvice(new ExceptionAdvisor());
TestBean proxy = (TestBean) pf.getProxy();
try {
proxy.method1();
} catch (Exception ignore) {
}
try {
proxy.changeToNumber("amigo");
} catch (Exception ignore) {
}
}
/**
* 对未知异常的处理.
* @param method
* @param args
* @param target
* @param ex
* @throws Throwable
* @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a>
* Creation date: 2007-7-24 - 下午03:35:02
*/
public void afterThrowing(Method method, Object[] args, Object target,
Exception ex) throws Throwable {
System.out.println("*************************************");
System.out.println("Error happened in class: " + target.getClass().getName());
System.out.println("Error happened in method: " + method.getName());
for (int i = 0; i < args.length; i++) {
System.out.println("arg[" + i + "]: " + args[i]);
}
System.out.println("Exception class: " + ex.getClass().getName());
System.out.println("*************************************");
}
/**
* 对NullPointerException异常的处理
* @param method
* @param args
* @param target
* @param ex
* @throws Throwable
* @author <a href="mailto:xiexingxing1121@126.com">AmigoXie</a>
* Creation date: 2007-7-24 - 下午01:17:35
*/
public void afterThrowing(Method method, Object[] args, Object target,
NullPointerException ex) throws Throwable {
System.out.println("*************************************");
System.out.println("Error happened in class: " + target.getClass().getName());
System.out.println("Error happened in method: " + method.getName());
for (int i = 0; i < args.length; i++) {
System.out.println("args[" + i + "]: " + args[i]);
}
System.out.println("Exception class: " + ex.getClass().getName());
System.out.println("*************************************");
}
}
用spring boot的ControllerAdvice 只能是拦截controller类
http://www.blogjava.net/amigoxie/archive/2007/07/24/132142.html