Spring------异常通知

前提

        1.只有切点报错才会执行

         2.需要按照一定的规则自己写方法

实现步骤 (AspectJ 方式)

         1.新建一个类,并实现一个方法 

public class MyThrowAdvice{
public void myexception(Exception e1){
System.out.println("执行异常通知
"+e1.getMessage());
}
}

         2.在 ApplicationContext.xml中配置相关信息

<bean id="mythrow"
class="com.bjsxt.advice.MyThrowAdvice"></bean>
<aop:config>
<aop:aspect ref="mythrow">
<aop:pointcut expression="execution(*com.bjsxt.test.Demo.demo1())" id="mypoint"/>
<aop:after-throwing method="myexception"pointcut-ref="mypoint" throwing="e1"/>
</aop:aspect>
</aop:config>

<bean id="demo" class="com.bjsxt.test.Demo"></bean>

第二种实现 (shchema-base实现)

        规则:类必须实现throwsAdvice 接口,方法中必须有一个叫afterThrowing的   参数为1个或者4个,异常类型要与切点报的异常类型一致  

第一步:创建类并声明函数

public class MyThrow implements ThrowsAdvice{
// public void afterThrowing(Method m, Object[] args,Object target, Exception ex) {
// System.out.println("执行异常通知");
// }
public void afterThrowing(Exception ex) throws Throwable {
  System.out.println("执行异常通过-schema-base 方式");
}
}

第二步:配置applicationContext.xml

<bean id="mythrow"
class="com.bjsxt.advice.MyThrow"></bean>
<aop:config>
<aop:pointcut expression="execution(*com.bjsxt.test.Demo.demo1())" id="mypoint"/>
<aop:advisor advice-ref="mythrow"pointcut-ref="mypoint" />
</aop:config>
<bean id="demo" class="com.bjsxt.test.Demo"></bean>

这里没有使用到aps:aspect

猜你喜欢

转载自blog.csdn.net/weixin_41298572/article/details/89051474