*本文主要介绍,是如何使用aop切面处理项目中的程序出现异常问题的
1.首先定义一个异常切面类:
/**
*
* 异常切面.
*
*/
public class BuziExceptionAspect {
//日志实现. TODO
// ProceedingJoinPoint:用于环绕通知,使用proceed()方法来执行目标方法:
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
//返回当前连接点签名
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature)signature;
//获取的targetMethod对象是接口上的方法
Method targetMethod = methodSignature.getMethod();
//目标对象的方法
Method realTargetMethod = joinPoint.getTarget().getClass().getDeclaredMethod(signature.getName(), targetMethod.getParameterTypes());
Class targetClass = joinPoint.getTarget().getClass();
Object result = null;
//目标对象方法上或类上有BuziExceptionHandler注解, 而且返回值为ResultObject才拦截.
if( (realTargetMethod.isAnnotationPresent(BuziExceptionHandler.class) ||
targetClass.isAnnotationPresent(BuziExceptionHandler.class)) &&
realTargetMethod.getReturnType() == ResultObject.class){
try{
//执行目标方法
result = joinPoint.proceed();
}catch (BuziException be){
be.printStackTrace();
//处理异常(返回异常信息)
result = ResultObject.result(be.getReturnCodeItem(),null);
}catch (Exception e){
e.printStackTrace();
result = ResultObject.systemErrorResult();
}
}else{
result = joinPoint.proceed();
}
return result;
}
}
2.在spring.xml文件里进行配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!--定义异常切面类-->
<bean id="buziExceptionAspect" class="com.ftms.starter.common.aop.BuziExceptionAspect"/>
<aop:config>
<aop:aspect id="serviceExceptionHandler" ref="buziExceptionAspect">
<!--execution:用于匹配方法执行的连接点;修饰符:可选,如public、protected;
返回值类型:必填,可以是任何类型模式;“*”表示所有类型;方法名:必填,可以使用“*”进行模式匹配;-->
<aop:pointcut expression="execution(public * com.ec.ftms..*.*(..))" id="serviceExceptionPointCut"/>
<aop:around method="around" pointcut-ref="serviceExceptionPointCut"/>
</aop:aspect>
</aop:config>
</beans>
3.在需要使用切面异常类处理异常的方法或类上面声明该注解即可
注: 在Spring配置文件中,所以AOP相关定义必须放在aop:config标签下
,该标签下可以有aop:pointcut、aop:advisor、aop:aspect标签,配置顺序不可变。
<aop:pointcut>:用来定义切入点,该切入点可以重用;
<aop:advisor>:用来定义只有一个通知和一个切入点的切面;
<aop:aspect>:用来定义切面,该切面可以包含多个切入点和通知,而且标签内部的通知和切入点定义
是无序的;和advisor的区别就在此,advisor只包含一个通知和一个切入点。
。
。
。
*觉得有用可以关注博主哦,如果再不能相遇,祝你早午晚都安。。。