spring 用aop方式植入事務,也可以自己將事務管理對象註入到service層,但很明顯,aop方式更靈活,更強大,用aop方式的spring事務管理後,在dao層就不再需要任何的hibernate事務瞭,在service 層調用Dao也不需要再去管事務的問題瞭,可以一心寫邏輯就oK瞭,當service需要事務時隻需要將spring 管理的事務aop切入這個service ,這個service就使用事務瞭。代碼如下:
[html]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:tx="https://www.springframework.org/schema/tx"
xmlns:aop="https://www.springframework.org/schema/aop"
xsi:schemaLocation="
https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-3.0.xsd
https://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx-3.0.xsd
https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
default-lazy-init="false">
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice> www.aiwalls.com
<aop:config>
<aop:pointcut expression="execution(* org.vean.services.LogLoginService.*(..))" id="txcut"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txcut"/>
</aop:config>
</beans>
這就是一個spring的事務管理,aop切到的方法都將具備事務的特性。
註意:使用事務必需提供一個SessionFactory這是毋庸置疑的,但使用hibernate事務時一般將Session綁定到線程,隻需設置:hibernate.current_session_context_class=thread,
而使用spring 的事務時,就不是將Session綁定到線程瞭,而是將Session綁定的spring的一個管理Session的容器中,設置wei :hibernate.current_session_context_class=org.springframework.orm.hibernate3.SpringSessionContext,
如果沒有使用事務對應的Seesion綁定設置,程序就會報錯~,因為如果是 啟用spring事務時,那麼spring就會向SpringSessionContext要Session,如果Session沒有綁定到SpringSessionContext類中,結果可想而知瞭。
作者:vean_system