先前我們做過一個簡單的 IOC 容器,本文要繼續在它上面疊加 AOP(面向切面程式設計)功能。核心思路並不複雜:透過 JDK 的動態代理攔截方法呼叫,在真正的方法前後插入橫切關注點。
public class Intercept implements InvocationHandler {
/** 被代理的目標物件,也就是我們要在其方法前後加上業務邏輯的物件 */
private Object target;
/** 動態產生處理過後的代理物件(寫法固定) */
public Object bind(Object target) throws InstantiationException, IllegalAccessException {
this.target = target;
return Proxy.newProxyInstance(
this.target.getClass().getClassLoader(),
this.target.getClass().getInterfaces(),
this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result;
AOPModel model = null;
if (InterceptList.getInterceptMethod().containsKey(method.getName())) {
model = InterceptList.getInterceptMethod().get(method.getName());
this.monitor(model.getBefore(), model.getBefore_aspectName(), this.target);
result = method.invoke(this.target, args);
this.monitor(model.getAfter(), model.getAfter_aspectName(), this.target);
} else {
result = method.invoke(this.target, args);
}
return result;
}
/** 依是否注入橫切關注點,決定 before / after 是否呼叫 */
private void monitor(Object clazz, String aspectName, Object target) throws Exception {
if (clazz != null) {
Method[] methods = clazz.getClass().getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equals(aspectName)) {
method.invoke(clazz, target);
}
}
}
}
}
幾個設計選擇值得說明。bind 方法回傳的是 Proxy.newProxyInstance 產生的代理物件,因此呼叫端拿到的其實不是原始物件,而是代理;所有方法呼叫都會先經過 invoke。而 invoke 裡用「方法名稱是否在 InterceptList 中」來決定要不要走攔截流程,這是個簡單但有效的路由判斷。
另一個值得注意的細節:bind 傳入的是目标物件的介面而非類別(getInterfaces())。這是 JDK 動態代理的硬性限制——它只能為介面產生代理,若目標類別沒有實作任何介面,就得改用 CGLIB 這類第三方方案。
public class IOC {
public IOC() {
Init();
}
public void Init() {
Field[] fields = getClass().getDeclaredFields();
for (Field field : fields) {
Inject inject = field.getAnnotation(Inject.class);
try {
if (inject != null) {
field.setAccessible(true);
if (inject.Intercept()) {
field.set(this, new Intercept().bind(
Class.forName(inject.ClassName().trim()).newInstance()));
} else {
field.set(this, Class.forName(inject.ClassName().trim()).newInstance());
}
}
} catch (Exception e) {
Logger.getLogger(getClass()).error(
"初始化容器異常:" + inject.ClassName().trim() + "初始化失敗", e);
}
}
}
}
關鍵在於註解多了一個 Intercept 屬性。容器在初始化時讀取每個欄位上的 @Inject,若 Intercept() 為 true,就用 new Intercept().bind(...) 把物件包一層代理再塞回去;否則照舊直接注入。也就是說,AOP 的開關是由使用者在宣告欄位時決定的,容器本身不需要知道任何切面細節。
public class TestIOC extends IOC {
public TestIOC() {
super();
}
@Inject(ClassName = "com.metarnet.Interfaces.imps.Interface1Impl", Intercept = true)
private Interface1 interface1;
@Inject(ClassName = "com.metarnet.Interfaces.imps.Interface1Impl2", Intercept = false)
private Interface1 interface2;
@Inject(ClassName = "com.metarnet.Interfaces.imps.After", Intercept = false)
private BeforeAfter after;
@Inject(ClassName = "com.metarnet.Interfaces.imps.Before", Intercept = false)
private BeforeAfter before;
/** 此方法可改為讀取設定檔後初始化 */
public void init() {
AOPModel model = new AOPModel();
model.setAfter(after);
model.setBefore(before);
model.setAfter_aspectName("SayAfter");
model.setBefore_aspectName("SayBefore");
InterceptList.getInterceptMethod().put("SayHello", model);
InterceptList.getInterceptList().add("interface1");
}
public static void main(String[] args) {
IOCInit.Init();
TestIOC ioc = new TestIOC();
ioc.init();
ioc.interface1.SayHello(); // 前後都會觸發切面
ioc.interface2.SayHello(); // 不攔截,直接執行
}
}
注意 init() 做的事:把「方法名稱 → 切面模型」的對應關係註冊進 InterceptList。這裡把 SayHello 對應到一個含 before/after 的 AOPModel,於是任何被代理物件呼叫 SayHello 時,都會先跑 SayBefore、再跑原方法、最後跑 SayAfter。
/** 需要橫切的模型 */
public class AOPModel {
private Object before; // before 橫切關注點
private Object after; // after 橫切關注點
private String before_aspectName; // before 要呼叫的方法名
private String after_aspectName; // after 要呼叫的方法名
// getter / setter 省略
}
/** 需要監聽的方法清單 */
public final class InterceptList {
private static HashMap<String, AOPModel> map = new HashMap<String, AOPModel>();
private static ArrayList<String> list = new ArrayList<String>();
public static HashMap<String, AOPModel> getInterceptMethod() {
return map;
}
public static ArrayList<String> getInterceptList() {
return list;
}
}
動手做輪子是理解原理最好的方式,但也要清楚它和成熟框架的差距:
切面粒度太粗。目前只支援「整個方法前」與「整個方法後」,無法處理例外拋出時的行為,也沒有 around 的完整語意。Spring AOP 之所以要設計 ProceedingJoinPoint,就是為了填這個洞。
攔截點靠方法名稱比對。InterceptList 用方法名稱當 key,代表不同類別的同名方法會互相干擾,也無法做「符合某前綴的所有方法」這種規則式匹配。真實場景需要 pointcut 表達式。
代理只能產生一次,且綁定介面。如前所述,沒實作介面的類別無法被代理。
靜態狀態有執行緒風險。InterceptList 的 map 與 list 都是 static 且未做同步,多執行緒註冊時會有問題。
這些限制並不代表這份程式碼沒價值——它把 AOP 的核心機制(動態代理 + 攔截 + 前後置通知)濃縮在幾十行內,讀懂它之後再看 Spring 的文件,會清楚很多。