学习java,挺好玩的呢

 

一、配置异常通知的步骤 (Aspectj方式)

  1、只有当切点报异常才能触发异常通知

  2、在spring中有Aspectj 方式提供了异常通知方法

    2.1 如果希望通过 schema-base 实现需要按照特定的要求自己编写方法

  3、实现步骤:

    3.1 新建类,在类中写任意名称的方法    

public class myExcetion {
    public void myexcetion(Exception e1){
        System.out.println("执行异常,tain"+e1.getMessage());
    }
}

    3.2 在spring配置文件中配置

      3.2.1 <aop:aspect ref="">:ref= 表示在哪个类中

      3.2.2 <aop:xxxx> 什么标签表示什么通知

      3.2.3 method:表示当触发这个通知时,调用哪个方法

<?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="myexcetion" class="com.bjsxt.myExcetion.myexcetion"></bean>
        <aop:config>
            <aop:aspect ref="myexcetion">
                <aop:pointcut expression="execution(* com.bjsxt.test.Test.demo1())" id="mypoint"/>
                <aop:after-throwing method="myExcetion" pointcut-ref="mypoint" throwing="e1"/>    throwing 表示异常处理的方法的参数名 (可以不再异常通知中声明异常对象)
            </aop:aspect>        
        </aop:config>
       <bean id="test" class="com.bjsxt.test.Test"></bean>    
  </beans>

 二、使用Schema-base 实现异常

  1、新建一个类实现ThrowsAdvice接口,且必须使用afterThrowing这个方法名。。

    1.1有两种参数方式

      必须有 1个 或 4个参数

    1.2 异常类型要与切点报的异常类型一致,

public class Mythrow implements ThrowsAdvice{
   // public void afterThrowing(Exception ex) throws Throwable {
     //   System.out.println("执行异常通知11111");
    //}

    public void afterThrowing(Method m, Object[] args, Object target, Exception ex) {
        System.out.println("执行异常通知2222");
    }
}

  2、在applicationContext.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.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
        
        <bean id="mythrow" class="com.bjsxt.advice.Mythrow"></bean>
        <bean id="demo" class="com.bjsxt.test.Demo"></bean>
        <aop:config>
            <aop:pointcut expression="execution(* com.bjsxt.test.Demo.demo1())" id="mypoint"/>
            <aop:advisor advice-ref="mythrow" pointcut-ref="mypoint"/>
        </aop:config>
  </beans>

 

posted on 2018-12-19 10:29  axu521  阅读(2458)  评论(0编辑  收藏  举报

<