Spring中的异常消息处理

在Spring中可以对异常消息统一由Spring容器管理
1 异常出现的位置

package com.zxf.demo;

public class Demo1 {
    public void demo1(){
        int r=4/0;
        System.out.println("demo1");
    }
    public void demo2(){
        System.out.println("demo2");
    }
    public void demo3(){
        System.out.println("demo3");
    }
}

2 异常处理类,就是一个普通的方法类。它需要有Spring容器配置来管理

package com.zxf.advice;

public class MyThrowAdvice {
    public void myexeception(){
        System.out.println("执行了异常通知");
    }
}

3 Spring 配置文件
在这里插入图片描述

<?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.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="mybefore" class="com.zxf.advice.MyBeforeAdvice"/>
    <bean id="after" class="com.zxf.advice.MyAfterAdvice"/>
    <bean id="mythrow" class="com.zxf.advice.MyThrowAdvice"/><!--就是刚刚写的那个异常消息类 -->
<aop:config>
       <aop:pointcut id="aop1" expression="execution(* com.zxf.demo.*.*(..))"/>
       <!--* 代表所有的意思 -->
       <!--com.zxf.demo.Demo1.*(..)) Demo1类下的所有方法 -->
       <!--com.zxf.demo.*.*(..)) demo包下的所有类和方法 -->
    <aop:advisor advice-ref="after" pointcut-ref="aop1"/>
    <aop:advisor advice-ref="mybefore" pointcut-ref="aop1"/>
    <aop:aspect ref="mythrow"> <!--定义Spring异常处理 -->
        <aop:pointcut id="myex1" expression="execution(* com.zxf.demo.Demo1.demo1(..))"/><!--这里是有可能出现异常的地方,就是那个5/0的地方 -->
        <aop:after-throwing method="myexeception" pointcut-ref="myex1"/>
    </aop:aspect>
</aop:config>
<bean id="demo1" class="com.zxf.demo.Demo1"/>
<bean id="demo2" class="com.zxf.demo.Demo2"/>

</beans>

在这里插入图片描述
在这里插入图片描述

发布了137 篇原创文章 · 获赞 71 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/zhang6132326/article/details/105267374