日期:2014-05-17  浏览次数:20859 次

ThrowsAdvice不起作用
我定义了一个类,实现了ThrowsAdvice接口,在afterThrowing方法里输出“拦截异常”,可它不起作用,控制台只是输出普通的异常信息,没有输出我自己写的“拦截异常”几个字

Hi类
Java code

public class Hi {
    public  void sayHI(){        
        System.out.println("i say hi");
        try {
            throw new Exception("my exception");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



ThrowsAdvice类:
Java code

import org.springframework.aop.ThrowsAdvice;


public class MyThrowsAdvice implements ThrowsAdvice{
    public void afterThrowing(Exception ex){
        System.out.println("拦截异常");
        System.out.println(ex);        
    }
}



applicationContex.xml
HTML code

<?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"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
    <bean id="hi" class="Hi"/>
    <bean id="throw" class="MyThrowsAdvice"/>
    <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target">
            <ref bean="hi"/>
        </property>
        <property name="interceptorNames">
            <list>
                 <value>proxy</value>
            </list>
        </property>
    </bean>
</beans>



Test.java
Java code

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
        public static void main(String[] args) {
        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
        Hi h=(Hi)ac.getBean("proxy");
        h.sayHI();    
    }
}




------解决方案--------------------
不要在方法里捕获