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"/>
註解模式開發流程
- 切面類別標註
@Aspect 與 @Component。
- 定義切入點:
@Pointcut("execution(* com.service..*.*(..))")。
- 編寫通知方法:
@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>