首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring AOP 核心概念與兩種配置方式實戰總結

     編輯:Java 綜合教學

Spring AOP 核心概念與兩種配置方式實戰總結

AOP (Aspect-Oriented Programming) 是 OOP 的有力補充:OOP 是縱向繼承體系,AOP 是橫向切面抽取。將日誌、權限、事務等橫切關注點從業務邏輯中分離,封裝為可復用的切面,降低耦合、提升維護性。

AOP 核心術語

術語說明對應註解/配置
Aspect (切面)橫切邏輯的模組化封裝@Aspect / <aop:aspect>
Join Point (連接點)程式執行過程中的某個具體點 (方法呼叫、異常拋出等)—
Pointcut (切入點)匹配一組連接點的條件表達式@Pointcut / <aop:pointcut>
Advice (通知/增強)在切入點執行的具體動作前置/後置/環繞/例外/返回
Weaving (織入)將切面應用到目標物件的過程編譯期/類載入期/執行期

實現技術對比

  • 動態代理 (JDK / CGLIB):執行期產生代理類,Spring 預設策略。介面用 JDK,類用 CGLIB
  • 靜態織入 (AspectJ):編譯期修改位元碼,效能更好但需特殊編譯器

方式一:XML 配置 (適用於日誌、事務等通用切面)

<!-- 切面 Bean -->
<bean id="serviceAspect" class="cn.ysh.studio.spring.aop.aspect.ServiceAspect"/>

<aop:config>
    <aop:aspect id="simpleAspect" ref="serviceAspect">
        <!-- 切入點:service 包下所有類的所有方法 -->
        <aop:pointcut expression="execution(* cn.ysh.studio.spring.aop.service..*(..))" id="simplePointcut"/>
        
        <aop:before pointcut-ref="simplePointcut" method="before"/>
        <aop:after pointcut-ref="simplePointcut" method="after"/>
        <aop:after-returning pointcut-ref="simplePointcut" method="afterReturn"/>
        <aop:after-throwing pointcut-ref="simplePointcut" method="afterThrow" throwing="ex"/>
    </aop:aspect>
</aop:config>

方式二:註解配置 (現代專案主流)

啟用掃描與自動代理:

<context:component-scan base-package="cn.ysh.studio.spring.aop"/>
<aop:aspectj-autoproxy proxy-target-class="true"/>

切面類實作:

@Component
@Aspect
public class ServiceAspect {
    @Pointcut("execution(* cn.ysh.studio.spring.aop.service..*(..))")
    public void aspect() {}
    
    @Before("aspect()")
    public void before(JoinPoint jp) { /* 前置邏輯 */ }
    
    @After("aspect()")
    public void after() { /* 後置邏輯 (finally) */ }
    
    @Around("aspect()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable { 
        /* 環繞:可控制是否執行目標方法、修改參數/返回值 */
        return pjp.proceed(); 
    }
    
    @AfterReturning("aspect()")
    public void afterReturn(Object result) { /* 正常返回後 */ }
    
    @AfterThrowing(pointcut="aspect()", throwing="ex")
    public void afterThrow(Exception ex) { /* 拋出異常後 */ }
}

五種通知類型對比

通知類型執行時機典型用途能否阻止目標執行
@Before目標方法前權限檢查、參數驗證否 (拋異常可中斷)
@After目標方法後 (無論正常/異常)資源清理、日誌記錄否
@Around包裹目標方法事務控制、效能監控、快取是 (不呼叫 proceed)
@AfterReturning正常返回後返回值處理、快取存入否
@AfterThrowing拋出異常後異常日誌、告警通知否

最佳實踐建議

  • 切入點表達式盡量精確,避免誤攔截非目標方法
  • @Around 功能最強但也最複雜,務必呼叫 pjp.proceed() 否則目標方法不會執行
  • 事務管理建議直接用 @Transactional,而非手寫 AOP
  • 大量切面時注意效能:考慮編譯期織入 (AspectJ) 或減少不必要的攔截
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved