8Spring AOP窃梦空间之三 ——AfterThrowing
8Spring AOP盗梦空间之三 ——AfterThrowing
书接上回
话说LEO在日本人打盹的时候盗取密码。电影中,梦境里日本人摸了地毯发现材质不对,知道被盗梦了,就开始与LEO团队扭打起来。发现了异常LEO需要尽快逃跑。这样需要LEO可以对日本人haveNap方法抛出异常进行监听并处理。
Spring提供了这种方式,@AfterThrowing用于监听宿主的异常,并处理异常。
1、Person代码修改如下
2、LeoIncept代码修改如下
3、测试代码
输出结果
书接上回
话说LEO在日本人打盹的时候盗取密码。电影中,梦境里日本人摸了地毯发现材质不对,知道被盗梦了,就开始与LEO团队扭打起来。发现了异常LEO需要尽快逃跑。这样需要LEO可以对日本人haveNap方法抛出异常进行监听并处理。
Spring提供了这种方式,@AfterThrowing用于监听宿主的异常,并处理异常。
1、Person代码修改如下
package com.spring.service; import org.springframework.stereotype.Component; @Component public class Person { public int haveNightmare() throws Exception { System.out.println(this.getClass().getName()); System.out.println("做恶梦"); int password = 5/0;//抛出异常 return password; } }
2、LeoIncept代码修改如下
package com.spring.aop; import java.lang.reflect.Method; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.aop.AfterReturningAdvice; import org.springframework.stereotype.Component; @Aspect @Component public class LeoIncept{ @AfterThrowing(throwing="arg0",pointcut ="execution(public int com.spring.service.Person.haveNightmare())") public void stealPassword(Exception arg0) throws Throwable { System.out.println(this.getClass().getName()); System.out.println("异常原因:"+arg0.getMessage());//输出异常原因 System.out.println("出现异常了,快跑"); } }
3、测试代码
package com.spring.service.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.service.Person; public class PersonTest { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext ctx = new ClassPathXmlApplicationContext("springbeans.xml"); Person person = (Person) ctx.getBean("person"); try { person.haveNightmare(); } catch (Exception e) { // TODO Auto-generated catch block } } }
输出结果
com.spring.service.Person 做恶梦 com.spring.aop.LeoIncept 异常原因:/ by zero 出现异常了,快跑