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

Spring AOP 完整配置指南:XML 與註解雙模式詳解

     編輯:Java 相關知識

AOP 核心概念

  • 切面:橫切關注點(如日誌、事務、安全)的模組化封裝。
  • 連接點:程式執行的某個點(Spring 僅支援方法執行)。
  • 切入點:匹配連接點的條件表達式(如 execution(* com.service..*.*(..)))。
  • 通知:切面在特定連接點執行的動作(前置、後置、環繞、例外、最終)。
  • 織入:將切面應用到目標對象建立代理的過程。

Spring AOP 依賴套件

aspectjweaver.jar, aspectjrt.jar, cglib-nodep-2.1-3.jar

啟用 AOP 支援

XML 命名空間

<beans xmlns:aop="https://www.springframework.org/schema/aop"
       xsi:schemaLocation="... https://www.springframework.org/schema/aop/spring-aop.xsd">

註解模式啟用

<aop:aspectj-autoproxy proxy-target-class="true"/>

註解模式開發流程

  1. 切面類別標註 @Aspect 與 @Component。
  2. 定義切入點:@Pointcut("execution(* com.service..*.*(..))")。
  3. 編寫通知方法:
    • @Before("pointcutName()") 前置通知
    • @AfterReturning(pointcut="pointcutName()", returning="result") 後置通知
    • @Around("pointcutName()") 環繞通知(需手動呼叫 pjp.proceed())
    • @AfterThrowing 例外通知
    • @After 最終通知

XML 模式配置範例

<aop:config>
    <aop:aspect id="logAspect" ref="loggingAspect">
        <aop:pointcut id="serviceMethods" expression="execution(* com.service..*.*(..))"/>
        <aop:before pointcut-ref="serviceMethods" method="beforeLog"/>
        <aop:after-returning pointcut-ref="serviceMethods" method="afterLog"/>
    </aop:aspect>
</aop:config>

Spring 宣告式事務管理

註解模式

<tx:annotation-driven transaction-manager="txManager"/>
@Transactional // 標註於 Service 方法或類別

XML 模式

<tx:advice id="txAdvice" transaction-manager="txManager">
    <tx:attributes>
        <tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>
        <tx:method name="*"/>
    </tx:attributes>
</tx:advice>
<aop:config>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/>
</aop:config>

PropertyPlaceholderConfigurer 外部配置載入

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <value>classpath:jdbc.properties</value>
    </property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${driver}"/>
    <property name="url" value="${url}"/>
    <property name="username" value="${username}"/>
    <property name="password" value="${password}"/>
</bean>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved