在Spring中使用JTA事务管理
4. Spring中相应的配置
让应用服务器提供JNDI数据源管理和JTA事务后,Spring肩上的担子减轻了许多,Spring要做的只是简单地引用JNDI的数据源,并启用JtaTransactionManager就可以了。
代码清单 4 applicationContext-jta-tomcat.xml:使用应用服务器的JTA支持
①使用Tomcat JNDI的数据源<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
②只需要指定一个JTA事务管理器就可以了,Spring会自动使用Tomcat中的JTA事务功能<jee:jndi-lookup id="topicDS" jndi-name="java:comp/env/jdbc/topicDS" />
<jee:jndi-lookup id="postDS" jndi-name="java:comp/env/jdbc/postDS" />
<bean id="topicTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="topicDS" />
</bean>
<bean id="postTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="postDS" />
</bean>
<bean id="topicDao" class="com.baobaotao.dao.jdbc.TopicJdbcDao">
<property name="jdbcTemplate" ref="topicTemplate" />
</bean>
<bean id="postDao" class="com.baobaotao.dao.jdbc.PostJdbcDao">
<property name="jdbcTemplate" ref="postTemplate" />
</bean>
<bean id="bbtForum" class="com.baobaotao.service.impl.BbtForumImpl">
<property name="topicDao" ref="topicDao" />
<property name="postDao" ref="postDao" />
</bean>
在①处,我们通过Spring jee命名空间提供的<jee:jndi-lookup>标签获取应用服务器中的JNDI资源,并将它们声明为一个Bean以供持久化模板类引用。<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>
<tx:annotation-driven transaction-manager="txManager" />
</beans>
和直接在Spring中使用JOTM不一样,这时,我们仅需要简单地配置一个JtaTransactionManager就可以了,该事务管理器将自动将JTA事务委托给应用程序器。
Spring引用Java EE应用服务器 JTA事务功能和Tomcat+JOTM提供JTA事务功能的配置步骤基本相似,相信大家可以对照这个实例完成相应的配置。另外,这里的实例采用了Spring JDBC作为持久层实现技术,你完全可以通过少量的调整将其应用到JPA、Hibernate、iBatis等持久化实现技术中。
0
相关文章
