靜態代理是 AOP 最基礎的形式:代理類在編譯期就已確定,直接包裝目標物件。雖然 Spring 實際運行使用動態代理,但理解靜態代理有助於掌握 AOP 核心概念——核心業務與橫切關注點分離。
package aop_001;
public interface G3Student {
void studyAtHome(String core);
void studyAtSchool(String core);
}
package aop_001;
public class G3Student_boy implements G3Student {
@Override
public void studyAtHome(String core) {
System.out.println(core + "在 HOME 學習");
}
@Override
public void studyAtSchool(String core) {
System.out.println(core + "在 SCHOOL 學習");
}
}
package aop_001;
public class G3Student_proxy implements G3Student {
private G3Student student; // 組合目標介面
public G3Student_proxy(String sex) {
if ("boy".equals(sex)) {
student = new G3Student_boy();
} else {
student = new G3Student_girl(); // 假設存在
}
}
@Override
public void studyAtHome(String core) {
// 前置增強:準備飯菜
System.out.println("代理:準備買菜");
System.out.println("代理:準備洗菜");
System.out.println("代理:準備炒菜");
System.out.println("代理:準備煮飯");
System.out.println("-----------------");
student.studyAtHome(core); // 委派核心業務
// 後置增強:準備補品
System.out.println("-----------------");
System.out.println("代理:購買補品");
System.out.println("代理:熬製補品");
System.out.println("代理:加入佐料");
System.out.println();
}
@Override
public void studyAtSchool(String core) {
// 相同增強邏輯重複出現 → 程式碼冗餘
System.out.println("代理:準備買菜");
System.out.println("代理:準備洗菜");
System.out.println("代理:準備炒菜");
System.out.println("代理:準備煮飯");
System.out.println("-----------------");
student.studyAtSchool(core);
System.out.println("-----------------");
System.out.println("代理:購買補品");
System.out.println("代理:熬製補品");
System.out.println("代理:加入佐料");
System.out.println();
}
}
package aop_001;
public class Test {
public static void main(String[] args) {
G3Student proxy = new G3Student_proxy("boy");
proxy.studyAtHome("小明");
proxy.studyAtSchool("小明");
}
}
代理:準備買菜 代理:準備洗菜 代理:準備炒菜 代理:準備煮飯 ----------------- 小明在 HOME 學習 ----------------- 代理:購買補品 代理:熬製補品 代理:加入佐料 代理:準備買菜 代理:準備洗菜 代理:準備炒菜 代理:準備煮飯 ----------------- 小明在 SCHOOL 學習 ----------------- 代理:購買補品 代理:熬製補品 代理:加入佐料
這正是動態代理(JDK Proxy / CGLIB)與 Spring AOP 要解決的問題:在執行期動態生成代理,將增強邏輯集中在切面中,實現真正的關注點分離。下一篇將詳細介紹動態代理實作。