業務邏輯中常夾雜日誌、安全、事務等橫切關注點。若硬編碼在業務方法中,會導致代碼臃腫、難維護、重複度高。Spring AOP 提供聲明式方式將橫切邏輯與業務邏輯分離。
execution(* com.service.*.*(..)))默認策略:有接口用 JDK,否則用 CGLIB。可通過 proxy-target-class="true" 強制 CGLIB。
// 1. 業務接口與實現
public interface Biz { void doBiz(); }
@Component class BizImpl implements Biz {
public void doBiz() { System.out.println("doing biz"); }
}
// 2. 切面類
@Aspect @Component
class LoggingAspect {
@Before("execution(* com.demo.Biz.doBiz(..))")
public void logBefore() { System.out.println("this is a advice"); }
}
// 3. 配置啟用
@Configuration @EnableAspectJAutoProxy
class AopConfig {}
// 4. 測試
ApplicationContext ctx = new AnnotationConfigApplicationContext(AopConfig.class);
ctx.getBean(Biz.class).doBiz();
// 輸出:this is a advice → doing biz
AbstractAutoProxyCreator 後置處理器識別需代理 BeanCglibAopProxy 創建代理對象(Enhancer 子類化)CglibMethodInvocation.proceed()Advice.invoke() → invocation.proceed() → 目標方法關鍵點:advised.getInterceptorsAndDynamicInterceptionAdvice() 根據 Pointcut 匹配構建攔截器鏈。
Spring AOP 以運行期動態代理實現橫切邏輯解耦,核心在於ProxyFactory決策代理類型與MethodInterceptor鏈式調用。理解其原理有助於排查代理失效、性能調優及自定義擴展。