spring中的事務控制
阿新 • • 發佈:2019-02-11
我們之前學了動態代理,而關於實物這塊,在每個service方法中總就那麼幾句話,而且地方也是固定的,所以我們也考慮用動態代理來解決它,只是在spring中,框架已經為我們寫好了通知類,我們直接配置就好了,跟之前AOP配置稍微有點不同,事務有它自己的配法,不過也差不多,看程式碼:
這是我寫的一個方法,模擬轉賬:
public void changeMoney(int i,int j,int money){ jt.update("update user set money = money - ? where id = ?", money,i); int x = 1/0; jt.update("update user set money = money + ? where id = ?", money,j); }
不配置事務時,i 的錢減少了,而 j 的錢沒有增多。
現在我們在xml檔案新增事務控制配置:
注意配置事務標籤先要匯入相關約束及 jar 包
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <!-- 第一步:配置事務管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="ds"></property> </bean> <!-- 第二步:配置通知,但因為你要寫的那幾個通知什麼時候執行怎麼執行都是固定的,所以spring幫我們寫了 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!-- 第三步:配置事務的屬性,具體參照下面的圖 --> <tx:attributes> <tx:method name="*" propagation="REQUIRED" read-only="true"/> </tx:attributes> </tx:advice> <!-- 第四步:配置通知和切入點的關係,形成一個完整的切面 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.dimples.*.impl.*.*(..))"/> </aop:config> </beans>
可以看到配置方法其實和原始的AOP配置很像,只不過多出了事務屬性的配置。下面這是事務屬性詳解:
然後我們還可以使用XML搭配註解的方式來配置事務:
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="ds"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager"/>
然後在需要事務的方法上加註解就行了:
@Transactional
public void changeMoney(int i,int j,int money){
jt.update("update user set money = money - ? where id = ?", money,i);
int x = 1/0;
jt.update("update user set money = money + ? where id = ?", money,j);
}
註解可以寫在介面上、類上、方法上。寫在介面上代表所有實現類都有事務,寫在類上表示所有方法都有事務,寫在方法上則表示該方法有事務,優先順序遵循就近原則!至於事務的屬性,我們可以在@Transactionl後面跟著配置。