8Spring AOP盗梦空间之三 ——AfterThrowing

书接上回

话说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
出现异常了,快跑
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值