三者結合構成輕量級 J2EE 解決方案。
| 類型 | 特點 |
|---|---|
| 編程式 | 靈活但代碼量大、重複代碼多 |
| 聲明式 | 更靈活方便,推薦使用 |
Connection conn = null;
try {
conn = DBConnectionFactory.getConnection();
conn.setAutoCommit(false);
// do something
conn.commit();
} catch (Exception e) {
conn.rollback();
} finally {
// 複雜的資源關閉邏輯,易疏漏拋出異常
}
代碼冗長、易遺漏 try/catch、資源關閉易出錯。
PlatformTransactionManager:事務管理基礎介面TransactionDefinition:事務屬性定義TransactionStatus:當前事務狀態,可提交/回滾TransactionDefinition td = new TransactionDefinition();
TransactionStatus ts = transactionManager.getTransaction(td);
try {
// do sth
transactionManager.commit(ts);
} catch (Exception e) {
transactionManager.rollback(ts);
}
void add() {
transactionTemplate.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus ts) {
// do sth
return null;
}
});
}
需注入事務管理器。Template 封裝了提交/回滾邏輯。
基於 IoC + AOP,提供 TransactionInterceptor 與 TransactionProxyFactoryBean。
<bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager"><ref bean="transactionManager"/></property>
<property name="transactionAttributeSource">
<value>com.test.UserManager.*=PROPAGATION_REQUIRED</value>
</property>
</bean>
<bean id="userManager" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces"><value>com.test.UserManager</value></property>
<property name="interceptorNames">
<list><idref local="transactionInterceptor"/></list>
</property>
</bean>
<bean id="userManager" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager"><ref bean="transactionManager"/></property>
<property name="target"><ref local="userManagerTarget"/></property>
<property name="transactionAttributes">
<props>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
方法名模式匹配定義事務屬性,支援傳播行為、只讀等屬性。
若需業務驗證等非事務切面,可結合 TransactionTemplate + 多攔截器。Spring AOP 提供三類 Advice:前置、後置、拋出異常增強。