項目結構

業務代碼
@Component("hello")
public class HelloImpl implements Hello
{
// 定義一個簡單方法,模擬應用中的業務邏輯方法
public void foo()
{
System.out.println("執行Hello組件的foo()方法");
}
// 定義一個addUser()方法,模擬應用中的添加用戶的方法
public int addUser(String name , String pass)
{
System.out.println("執行Hello組件的addUser添加用戶:" + name);
if(name.length() < 3 || name.length() > 10)
{
throw new IllegalArgumentException("name參數的長度必須大於3,小於10!");
}
return 20;
}
}
@Component("world")
public class WorldImpl implements World
{
// 定義一個簡單方法,模擬應用中的業務邏輯方法
public void bar()
{
System.out.println("執行World組件的bar()方法");
}
}
定義切面Bean

說明:
如果ex的類型是NullPointer-Exception,則只匹配該類型的異常;
@Aspect
public class RepairAspect
{
// 匹配org.crazyit.app.service.impl包下所有類的、
// 所有方法的執行作為切入點
@AfterThrowing(throwing="ex"
, pointcut="execution(* org.crazyit.app.service.impl.*.*(..))")
// 聲明ex時指定的類型會限制目標方法必須拋出指定類型的異常
// 此處將ex的類型聲明為Throwable,意味着對目標方法拋出的異常不加限制
public void doRecoveryActions(Throwable ex)
{
System.out.println("目標方法中拋出的異常:" + ex);
System.out.println("模擬Advice對異常的修復...");
}
}
配置
<?xml version="1.0" encoding="GBK"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<!-- 指定自動搜索Bean組件、自動搜索切面類 -->
<context:component-scan base-package="org.crazyit.app.service
,org.crazyit.app.aspect">
<context:include-filter type="annotation"
expression="org.aspectj.lang.annotation.Aspect"/>
</context:component-scan>
<!-- 啟動@AspectJ支持 -->
<aop:aspectj-autoproxy/>
</beans>
測試
public class BeanTest
{
public static void main(String[] args)
{
// 創建Spring容器
ApplicationContext ctx = new
ClassPathXmlApplicationContext("beans.xml");
Hello hello = ctx.getBean("hello" , Hello.class);
hello.foo();
hello.addUser("悟空" , "7788"); //拋出異常--名字長度不夠
World world = ctx.getBean("world" , World.class);
world.bar();
}
}

說明:
從上面可以看出,雖然AfterThrowing可以對目標方法的異常進行處理,但這種處理方法和直接使用catch捕捉不同,如下:
- catch:意味着完全處理該異常,如果catch語句中沒有重新拋出新異常,則該方法可以正常結束;
- AfterThrowing:雖然處理了該異常,但它不能完全處理異常,該異常依然會傳播到上一級調用者。
鏈接:
《@AfterReturning增強處理簡單示例》
http://www.cnblogs.com/ssslinppp/p/4633496.html
《@After后向增強處理簡單示例》
http://www.cnblogs.com/ssslinppp/p/4633427.html
《@Before前向增強處理簡單示例》
http://www.cnblogs.com/ssslinppp/default.html?page=7
附件列表