Spring AOP创建Throwdvice实例

2019-08-09 00:00:00 spring 创建 实例

         1、异常发生的时候,通知某个服务对象做处理

         2、实现throwsAdvice接口

 

接口实现:

 

public interface IHello {
   public void sayHello(String str) throws Exception;
}
public class Hello implements IHello  {
    @Override
    public void sayHello(String str) throws Exception {
    	System.out.println("你好"+str);
    	//测试抛出异常
    	throw new Exception("故意造成异常!");
    }
}

 

 SayThrowAdvice文件:

public class SayThrowAdvice implements ThrowsAdvice {

	public void afterThrowing(Method method,Object[] objs,Object target,Throwable ta)
	{
		System.out.println("我捕获的异常是-> "+ta+" =====, 在方法 "+method+"抛出了异常");
	}
}

  

applicationContext.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" 
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
    <!-- 建立目标对象实例 -->
	<bean id="bean_hello" class="com.pb.Hello" />
	<!-- 创建执行前advice实例 -->
	<bean id="sba" class="com.pb.SayBeforeAdvice" />
	<!-- 创建执行后advice实例 -->
	<bean id="sfa" class="com.pb.SayAfterAdvice" />
	<!-- 创建Around advice实例 -->
	<bean id="ssd" class="com.pb.SayAroundAdvice" />
	<!-- 创建Throw advice实例 -->
	<bean id="sta" class="com.pb.SayThrowAdvice" />
	<!-- 建立代理对象 -->
	<bean id="helloProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
	    <!-- 设置代理的接口 -->
	    <property name="proxyInterfaces">
			<value>com.pb.IHello</value>
		</property>
		<!-- 设置目标对象实例 -->
		<property name="target">
			<ref bean="bean_hello"/>
		</property>
		<!-- 设置Advice实例 -->
		<property name="interceptorNames">
			<list>
			   <!-- 
			 	<value>sba</value>
			 	<value>sfa</value>
			 	 -->
			 	 <value>ssd</value>
			 	 <value>sta</value>
			</list>
		</property>
	</bean>
</beans>

 主方法文件:

public class MainTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
	    ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
	    
	    IHello hello=(IHello)context.getBean("helloProxy");
	    
	    try {
	    	hello.sayHello("访客");
		} catch (Exception e) {
			// TODO: handle exception
		}
	    
	}

}

 执行效果:

《Spring AOP创建Throwdvice实例》

《Spring AOP创建Throwdvice实例》

 

相关文章