Spring声明式事务学习
快过年了,没什么事情,看了一下spring2.0中的声明式的事务处理,自己做了一个小例子,是JTA方式的。 dataAccessContext-jta.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
<jee:jndi-lookup id="DataSource" jndi-name="java:comp/env/jdbc/DataSource"/>
<jee:jndi-lookup id="DataSource2" jndi-name="java:comp/env/jdbc/DataSource2"/>
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>
<bean id="UserDao" class="dao.UserDaoImpl">
<property name="ds" ref="DataSource"/>
<property name="ds2" ref="DataSource2"/>
</bean>
</beans>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<aop:config>
<aop:advisor pointcut="execution(* *..UserDao.*(..))" advice-ref="txAdvice"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="insert*" rollback-for="java.sql.SQLException"/>
<tx:method name="update*"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
</beans>
事务的回滚和边界的划分是正确的,最后回滚的时候有连接泄漏,可能是抛出的SQLException的问题,如果是抛出的是其他的业务层的异常的话,我想就不会有连接泄漏的问题,我测试的时候一时也想不到什么好的业务异常,就弄了个SQLException,试了一下。在这一点上,是比ejb要好,检查异常,也能回滚事务。
web.xml
UserDao.java
UserDaoImpl.java