三.配置异常通知的步骤(AspectJ 方式)
1.只有当切点报异常才能触发异常通知
2.在spring 中有AspectJ 方式提供了异常通知的办法
3.实现步骤:
3.1新建类,在类写任意名称的方法
public class MyThrowAdvice {
public void myException(Exception e){
System.out.println("执行异常通知!"+e.getMessage());
}
}
3.2在spring 配置文件中配置
3.2.1<aop:aspect>的ref 属性表示:方法在哪个类中.
3.2.2<aop: xxxx/> 表示什么通知
3.2.3method: 当触发这个通知时,调用哪个方法
3.2.4throwing: 异常对象名,必须和通知中方法参数名相同(可以不在通知中声明异常对象)
<!--配置demo类,方便Spring启动时进行创建-->
<bean id="demo" class="com.test.demo"></bean>
<!--配置异常通知提醒: (AspectJ 方式)-->
<bean id="mythrow" class="com.advice.MyThrowAdvice"></bean>
<aop:config>
<aop:aspect ref="mythrow">
<aop:pointcut id="mypoint" expression="execution(* com.test.demo.demo1())"/>
<aop:after-throwing method="myException" pointcut-ref="mypoint" throwing="e"/>
</aop:aspect>
</aop:config>
四.异常通知(Schema-based 方式实现)
1.新建一个类myThrow实现throwsAdvice 接口
1.1必须自己写方法,且必须叫afterThrowing
1.2有两种参数方式
1.2.1必须是 1 个或 4 个 , Spring倒序检查机制!有多个重载时,逆序进行执行!
异常类型要与切点报的异常类型一致;
import org.springframework.aop.ThrowsAdvice;
public class myThrow implements ThrowsAdvice {
// public void afterThrowing(Method m, Object[] args, Object target, Exception ex) {
// System.out.print("执行异常通知");
// }
public void afterThrowing(Exception e) throws Throwable {
System.out.println("执行异常通过-schema-base 方式");
}
}
2.在ApplicationContext.xml 配置 :
<beans>
<bean id="demo" class="com.test.demo"/>
<bean id="mythrow" class="com.advice.myThrow"></bean>
<aop:config>
<aop:pointcut id="mypoint" expression="execution(* com.test.demo.demo1())"/>
<aop:advisor advice-ref="mythrow" pointcut-ref="mypoint"/>
</aop:config>
</beans>