第一章:AOP 核心概念與基礎應用
1.1 AOP 核心思想
- ?面向切面編程:通過橫向抽取機制解決代碼重復問題(如日志、事務、安全等)
- ?核心優勢:不修改源代碼增強功能,提高代碼復用性和可維護性
1.2 基礎環境搭建(Maven 依賴)
<dependencies><!-- Spring Core --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.2.RELEASE</version></dependency><!-- AOP 支持 --><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.3</version></dependency><!-- 其他必要依賴 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency>
</dependencies>
1.3 事務管理案例實踐
AccountServiceImpl 核心方法
public void saveAll(Account acc1, Account acc2) {// 原始業務邏輯accountDao.save(acc1);accountDao.save(acc2);
}
動態代理實現事務增強
public class JdkProxy {public static Object getProxy(AccountService target) {return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),(proxy, method, args) -> {try {TxUtils.startTransaction();Object result = method.invoke(target, args);TxUtils.commit();return result;} catch (Exception e) {TxUtils.rollback();throw e;} finally {TxUtils.close();}});}
}
第二章:AOP 核心術語與 XML 配置
2.1 七大核心概念
- ?Joinpoint(連接點)?:可被攔截的方法(Spring 僅支持方法級別)
- ?Pointcut(切入點)?:實際被增強的方法集合
- ?Advice(通知)?:增強邏輯的具體實現
- ?Target(目標對象)?:被代理的原始對象
- ?Weaving(織入)?:將增強應用到目標對象的過程
- ?Proxy(代理)?:增強后生成的新對象
- ?Aspect(切面)?:切入點 + 通知的組合體
2.2 XML 配置實戰
Spring 配置模板
<aop:config><aop:aspect ref="txAspect"><aop:before method="beginTransaction"pointcut="execution(* com.example.service.*.*(..))"/></aop:aspect>
</aop:config>
切入點表達式詳解
execution([修飾符] 返回類型 包名.類名.方法名(參數))
- 常用通配符:
*
?匹配任意內容..
?匹配任意包路徑或參數列表- 示例:
execution(* com.example..*Service.*(..))
2.3 五種通知類型
通知類型 | XML 標簽 | 執行時機 |
---|---|---|
前置通知 | <aop:before> | 方法執行前 |
后置通知 | <aop:after-returning> | 方法正常返回后 |
異常通知 | <aop:after-throwing> | 方法拋出異常時 |
最終通知 | <aop:after> | 方法最終結束 |
環繞通知 | <aop:around> | 方法執行前后均可控制 |
環繞通知示例
public Object around(ProceedingJoinPoint pjp) throws Throwable {try {System.out.println("前置增強");Object result = pjp.proceed();System.out.println("后置增強");return result;} catch (Exception e) {System.out.println("異常處理");throw e;}
}
第三章:注解驅動 AOP 開發
3.1 快速入門
切面類配置
@Aspect
@Component
public class LogAspect {@Before("execution(* com.example.service.*.*(..))")public void logBefore(JoinPoint jp) {System.out.println("方法執行前: " + jp.getSignature());}
}
啟用 AOP 注解支持
<!-- XML 方式 -->
<aop:aspectj-autoproxy/><!-- 純注解方式 -->
@Configuration
@EnableAspectJAutoProxy
@ComponentScan("com.example")
public class AppConfig {}
3.2 注解通知類型
注解 | 等效 XML | 說明 |
---|---|---|
@Before | 方法執行前 | |
@AfterReturning | 方法正常返回后 | |
@AfterThrowing | 方法拋出異常時 | |
@After | 方法最終結束 | |
@Around | 環繞通知 |
3.3 最佳實踐建議
-
?切面組織原則:
- 按功能模塊劃分切面(如日志切面、事務切面)
- 使用
@Pointcut
統一管理切入點
@Aspect public class SystemArchitecture {@Pointcut("within(com.example.web..*)")public void inWebLayer() {} }
-
?性能優化技巧:
- 避免在切面中執行耗時操作
- 使用條件表達式減少不必要的增強
-
?常見問題排查:
- 確保 Aspect 類被 Spring 管理(添加@Component)
- 檢查切入點表達式是否匹配目標方法
- 確認是否啟用自動代理(@EnableAspectJAutoProxy)
第四章:AOP 應用場景與進階
4.1 典型應用場景
- ?聲明式事務管理
- ?統一日志記錄
- ?權限控制與安全檢查
- ?性能監控與統計
- ?異常統一處理
4.2 高級特性
組合切入點表達式
@Pointcut("execution(* com.example.dao.*.*(..))")
public void dataAccessOperation() {}@Pointcut("execution(* com.example.service.*.*(..))")
public void businessService() {}@Before("dataAccessOperation() || businessService()")
public void combinedPointcut() {// 組合邏輯
}
自定義注解實現 AOP
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AuditLog {}@Aspect
@Component
public class AuditAspect {@Around("@annotation(AuditLog)")public Object audit(ProceedingJoinPoint pjp) throws Throwable {// 審計邏輯實現}
}
通過系統學習 Spring AOP 的核心概念、配置方式和實踐技巧,開發者可以更高效地實現業務邏輯與非功能性需求的解耦,構建更健壯、可維護的企業級應用。