AOP(Aspect Oriented Programming,面向切面程式設計)是 Spring 最具代表性的特性之一。它把日誌、權限檢查、事務、異常處理這類「與主流程無關但到處都要寫」的程式碼抽離出來,讓業務邏輯回歸乾淨。Spring 官方也強烈建議以介面方式進行程式設計,這正好與 AOP 的代理機制相輔相成。
Spring 提供了三種攔截器:方法前攔截器、返回後攔截器與異常拋出攔截器。下面用一個完整範例把它們串起來。
// Service 介面
public interface IAopService {
public void withAop() throws Exception; // 將會被攔截
public void withoutAop() throws Exception; // 不會被攔截
}
public class AopServiceImpl implements IAopService {
private String name;
public void withAop() throws Exception {
System.out.println("有 AOP 的方法執行。name:" + name);
if (name.trim().length() == 0) {
throw new AccountException("name 屬性不能為空");
}
}
public void withoutAop() throws Exception {
System.out.println("沒有 AOP 的方法執行。");
}
public void setName(String name) { this.name = name; }
public String getName() { return this.name; }
}
實作 MethodBeforeAdvice,在目標方法被呼叫「之前」執行,常用於參數與狀態檢查:
import org.springframework.aop.MethodBeforeAdvice;
public class MethodBeforeInterceptor implements MethodBeforeAdvice {
// 參數分別為被呼叫的方法、方法參數、物件本身
public void before(Method method, Object[] args, Object instance) throws Throwable {
System.out.println("即將執行方法:" + method.getName());
if (instance instanceof AopServiceImpl) {
String name = ((AopServiceImpl) instance).getName();
if (name == null) {
throw new NullPointerException("name 不能為空");
}
}
}
}
實作 AfterReturningAdvice,在目標方法正常結束後取得返回值:
import org.springframework.aop.AfterReturningAdvice;
public class MethodAfterInteceptor implements AfterReturningAdvice {
// 參數分別為回傳值、被呼叫方法、方法參數、被攔截的物件
public void afterReturning(Object value, Method method, Object[] args, Object instance) throws Throwable {
System.out.println("方法:" + method.getName() + " 執行完畢,回傳值為:" + value);
}
}
實作 ThrowAdvice。它的參數設計相當靈活:前三個參數可省略,最後一個異常參數必填,因此可以寫多個方法分別捕捉不同型別的異常:
import org.springframework.aop.ThrowAdvice;
public class ThrowsInterceptor implements ThrowAdvice {
public void afterThrowing(Method method, Object[] args, Object instance, AccountException ex) throws Throwable {
System.out.println("方法:" + method.getName() + " 拋出了異常:" + ex);
}
public void afterThrowing(NullPointerException ex) throws Throwable {
System.out.println("拋出了異常:" + ex);
}
}
Service 實作類與攔截器之間沒有 setter/getter 可以互相對接,因此 Spring 必須借助代理類:先把攔截器安裝到 NameMatchMethodPointcutAdvisor,再把目標 Service 交給 ProxyFactoryBean,最後兩者組裝在一起。
<!-- 方法前攔截器安裝到 NameMatchMethodPointcutAdvisor -->
<bean id="aopMethodBeforeInterceptor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<property name="advice">
<bean class="com.clf.spring.MethodBeforeInterceptor"/>
</property>
<!-- 欲攔截的方法名 -->
<property name="mappedName" value="withAop"/>
</bean>
<!-- 以類似方式配置返回後攔截器 -->
<bean id="aopMethodAfterInterceptor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<property name="advice">
<bean class="com.clf.spring.MethodAfterInteceptor"/>
</property>
<property name="mappedName" value="withAop"/>
</bean>
<!-- 以類似方式配置異常攔截器 -->
<bean id="aopThrowsInterceptor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<property name="advice">
<bean class="com.clf.spring.ThrowsInterceptor"/>
</property>
<property name="mappedName" value="withoutAop"/>
</bean>
<!-- Service 實作類安裝到 ProxyFactoryBean -->
<bean id="aopService" class="org.springframework.aop.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>aopMethodBeforeInterceptor</value>
<value>aopMethodAfterInterceptor</value>
<value>aopThrowsInterceptor</value>
</list>
</property>
<property name="target">
<bean class="com.clf.spring.AopServiceImpl">
<property name="name" value="HelloSpring"/>
</bean>
</property>
</bean>
切面(Aspect):範例中 withAop()、withoutAop() 裡那些與主流程無關的程式碼,就是切面的具體體現,你可以把切面理解為一個「模組」。
通知(Advice):三個攔截器都實作了某個 AOP 介面,從類別名稱就能看出它們都是通知。一旦符合條件,Spring 便會派發通知,也就是執行那些真正要插入的程式碼。
切入點(Pointcut):配置時只指定 withAop() 使用攔截器,withoutAop() 則不套用,這套「往哪裡插入」的規則正是切入點,由 NameMatchMethodPointcutAdvisor 負責,且支援萬用字元。
一句話總結:切入點決定「插在哪裡」,通知決定「插入什麼」。
Spring 也提供更靈活的切入點設定,例如以正規表達式批次比對方法名稱:
<bean id="advisorTest" class="org.springframework.aop.support.RegexMethodPointcutAdvisor">
<property name="interceptor">
<ref local="someInterceptor"/>
</property>
<property name="pattern">
<list>
<value>.*get*</value>
<value>.*set*</value>
</list>
</property>
</bean>
把這套機制理解透徹,後續要遷移到 AspectJ 語法或註解式 AOP 都會輕鬆許多。