您的位置:首页 > 编程语言 > Java开发

使用Spring配置文件实现事务管理

2010-06-25 12:06 806 查看
在前面我们介绍的都是基于注解的方式来使用事务,现在来学习下基于XML的方式怎样来配置事务,先把PersonServiceBean.java里的注解去掉,
PersonServiceBean.java

Java代码



package cn.itcast.service.impl;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import cn.itcast.bean.Person;

import cn.itcast.service.PersonService;

public class PersonServiceBean implements PersonService {

private JdbcTemplate jdbcTemplate;

public void setDataSource(DataSource dataSource) {

this.jdbcTemplate = new JdbcTemplate(dataSource);

}

public void delete(Integer personid) throws Exception{

jdbcTemplate.update("delete from person where id=?", new Object[]{personid},

new int[]{java.sql.Types.INTEGER});

}

public Person getPerson(Integer personid) {

return (Person)jdbcTemplate.queryForObject("select * from person where id=?", new Object[]{personid},

new int[]{java.sql.Types.INTEGER}, new PersonRowMapper());

}

@SuppressWarnings("unchecked")

public List<Person> getPersons() {

return (List<Person>)jdbcTemplate.query("select * from person", new PersonRowMapper());

}

public void save(Person person) {

jdbcTemplate.update("insert into person(name) values(?)", new Object[]{person.getName()},

new int[]{java.sql.Types.VARCHAR});

}

public void update(Person person) {

jdbcTemplate.update("update person set name=? where id=?", new Object[]{person.getName(), person.getId()},

new int[]{java.sql.Types.VARCHAR, java.sql.Types.INTEGER});

}

}

package cn.itcast.service.impl;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import cn.itcast.bean.Person;
import cn.itcast.service.PersonService;

public class PersonServiceBean implements PersonService {
private JdbcTemplate jdbcTemplate;

public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}

public void delete(Integer personid) throws Exception{
jdbcTemplate.update("delete from person where id=?", new Object[]{personid},
new int[]{java.sql.Types.INTEGER});
}

public Person getPerson(Integer personid) {
return (Person)jdbcTemplate.queryForObject("select * from person where id=?", new Object[]{personid},
new int[]{java.sql.Types.INTEGER}, new PersonRowMapper());
}

@SuppressWarnings("unchecked")
public List<Person> getPersons() {
return (List<Person>)jdbcTemplate.query("select * from person", new PersonRowMapper());
}

public void save(Person person) {
jdbcTemplate.update("insert into person(name) values(?)", new Object[]{person.getName()},
new int[]{java.sql.Types.VARCHAR});
}

public void update(Person person) {
jdbcTemplate.update("update person set name=? where id=?", new Object[]{person.getName(), person.getId()},
new int[]{java.sql.Types.VARCHAR, java.sql.Types.INTEGER});
}
}


目前这个bean是不受Spring管理的,我们通过配置文件的方式,在XML文件中对这个bean进行事务配置。
如果我们采用基于XML方式来配置事务的话,beans.xml里的<tx:annotation-driven transaction-manager="txManager"/>
这个就不再需要使用,删掉。
我们介绍下,如何使用基于XML方式配置事务,

采用基于XML方式配置事务
--------------------------------------------------------------------

Xml代码



<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="dataSource"/>

</bean>

<aop:config>

<aop:pointcut id="transactionPointcut" expression="execution(* cn.itcast.service..*.*(..))"/>

<aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>

</aop:config>

<tx:advice id="txAdvice" transaction-manager="txManager">

<tx:attributes>

<tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>

<tx:method name="*"/>

<!--其它方法使用默认的事务行为-->

</tx:attributes>

</tx:advice>

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* cn.itcast.service..*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>
<tx:method name="*"/>
<!--其它方法使用默认的事务行为-->
</tx:attributes>
</tx:advice>


我们配置了一个<aop:config>,里面的切入点pointcut,它对哪些方法进行拦截呢?对cn.itcast.service这个包,及其子包底下的所有类的所有方法,实现拦截。 拦截到方法后,运用一个advisor(通知),这个通知大家要注意,Spring里面已经给我们提供了一个事务通知了,通过<aop:advisor advice-ref...这个配置把它引入进来,这个通知,使用了上面的切入点,也就是说当拦截到这些业务方法的执行的时候呢,它会交给txAdvice这个事务通知进行处理.
txAdvice这个bean的定义,实际上在Spring容器里它也会注册一个事务管理器,应该说是注册一个通知管理器,专门用来做事务处理的这么一个bean。

接下来配置beans.xml

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:context="http://www.springframework.org/schema/context"

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.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<context:property-placeholder location="classpath:jdbc.properties"/>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

<property name="driverClassName" value="${driverClassName}"/>

<property name="url" value="${url}"/>

<property name="username" value="${username}"/>

<property name="password" value="${password}"/>

<!-- 连接池启动时的初始值 -->

<property name="initialSize" value="${initialSize}"/>

<!-- 连接池的最大值 -->

<property name="maxActive" value="${maxActive}"/>

<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->

<property name="maxIdle" value="${maxIdle}"/>

<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->

<property name="minIdle" value="${minIdle}"/>

</bean>

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="dataSource"/>

</bean>

<aop:config>

<aop:pointcut id="transactionPointcut" expression="execution(* cn.itcast.service..*.*(..))"/>

<aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>

</aop:config>

<tx:advice id="txAdvice" transaction-manager="txManager">

<tx:attributes>

<tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>

<tx:method name="*"/>

</tx:attributes>

</tx:advice>

<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean">

<property name="dataSource" ref="dataSource"/>

</bean>

</beans>

<?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:context="http://www.springframework.org/schema/context"
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.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> 
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="${initialSize}"/>
<!-- 连接池的最大值 -->
<property name="maxActive" value="${maxActive}"/>
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="${maxIdle}"/>
<!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="${minIdle}"/>
</bean>

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>

<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* cn.itcast.service..*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>

<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>


配置好事务了,PersonServiceBean这业务bean就可以受事务管理了。现在就可以使用Spring里面的声明式事务对它进行管理了,现在做一下测试,看事务是否应用起来了。
打开单元测试,执行save方法,保存一些数据进去。。
PersonServiceTest.java

Java代码



package junit.test;

import org.junit.BeforeClass;

import org.junit.Test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.itcast.bean.Person;

import cn.itcast.service.PersonService;

public class PersonServiceTest {

private static PersonService personService;

@BeforeClass

public static void setUpBeforeClass() throws Exception {

try {

ApplicationContext cxt = new ClassPathXmlApplicationContext("beans.xml");

personService = (PersonService) cxt.getBean("personService");

} catch (RuntimeException e) {

e.printStackTrace();

}

}

@Test public void save(){

for(int i=10; i<15; i++)

personService.save(new Person("传智播客"+ i));

}

..................................

@Test public void delete(){

try {

personService.delete(3);

} catch (Exception e) {

e.printStackTrace();

}

}

..................................

}

package junit.test;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.itcast.bean.Person;
import cn.itcast.service.PersonService;

public class PersonServiceTest {
private static PersonService personService;

@BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
ApplicationContext cxt = new ClassPathXmlApplicationContext("beans.xml");
personService = (PersonService) cxt.getBean("personService");
} catch (RuntimeException e) {
e.printStackTrace();
}
}

@Test public void save(){
for(int i=10; i<15; i++)
personService.save(new Person("传智播客"+ i));
}

..................................

@Test public void delete(){
try {
personService.delete(3);
} catch (Exception e) {
e.printStackTrace();
}
}

..................................
}


现在数据库person表的记录如下:看图



为了进一步验证事务配置起作用了,我们可以这样做

Java代码



public void delete(Integer personid) throws Exception{

jdbcTemplate.update("delete from person where id=?", new Object[]{personid},

new int[]{java.sql.Types.INTEGER});

jdbcTemplate.update("delete from person_wrong_name where id=7");

}

public void delete(Integer personid) throws Exception{
jdbcTemplate.update("delete from person where id=?", new Object[]{personid},
new int[]{java.sql.Types.INTEGER});
jdbcTemplate.update("delete from person_wrong_name where id=7");
}


在PersonServiceBean.java的delete方法里面,执行两条update语句,默认情况下这两条语句都会在同一个事务里执行,如果说这个方法没有开启事务的话,这两条update语句会在各自的事务里执行(也就是说他们不能在同一事务里执行),我们通过这样来判断delete方法是否开了事务,如果开了事务,两条update语句就在同一事务里执行,如果没开事务,就会在各自的事务里执行,也就是说第二个update语句故意写错了,第二条语句会出错,它是否会引起第一条update语句的回滚呢?如果我们应用上了Spring的事务管理,他必然会一起回滚,如果没应用上的话,第一条update语句是会运行成功的。
运行单元测试的delete方法,

Java代码



@Test public void delete(){

try {

personService.delete(3);

} catch (Exception e) {

e.printStackTrace();

}

}

@Test public void delete(){
try {
personService.delete(3);
} catch (Exception e) {
e.printStackTrace();
}
}


JUnit显示出错,查看数据库person表记录,发现id为3和7的记录还在,如图:



说明开了事务,两条都不被删。
假如我们没有应用事务管理的话,在beans.xml里,把下面的语句注释掉

Xml代码



<!--

<aop:config>

<aop:pointcut id="transactionPointcut" expression="execution(* cn.itcast.service..*.*(..))"/>

<aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>

</aop:config>

<tx:advice id="txAdvice" transaction-manager="txManager">

<tx:attributes>

<tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>

<tx:method name="*"/>

</tx:attributes>

</tx:advice>

-->

<!--
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* cn.itcast.service..*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
-->


看下当我们没有应用Spring的事务管理器的时候,它是否能删除id=3这条记录(既是第一个update语句顺利提交不回滚)呢?
现在数据库person表的记录如下,看图:



运行单元测试的delete方法,JUnit说运行时出错,看数据库,如图:



id=3的记录不见了,id=7的记录还存在,这代表,事务管理器没有应用上,因为第一条update语句是在一个事务里执行,第二条update语句是在另一个事务里执行,因为它没有应用上Spring提供的事务管理,所以说他们两个update语句会在单独的事务中执行。 第一条是执行成功的,第二条是执行失败的。我们通过观察结果就可以看到它目前并没有应用上事务管理,所以一定要注意:以后在开发的时候,一定要确保你们的bean是受Spring的事务管理的。如果不受管理的话,你们就无法应用Spring给我们提供的这些功能,也就是说业务方法开启的时候给我们打开事务,在业务方法结束的时候根据运行情况如果没有抛出运行期例外的话,那么它就给我们提交事务,否则它就给我们回滚事务,这点大家是要注意的。

基于XML方式使用事务就给大家介绍完了,具体使用XML方式配置事务,还是使用注解方式配置事务,Spring开发团队就建议我们采用注解方式来配置事务,因为采用注解方式来使用事务的话,我们的配置可以做到精确控制,可以针对某一个方法,使用起来比较灵活。如果采用配置方式为某个业务方法定义某些事务行为的话,那么这个配置文件配置内容会很臃肿,所以Spring的开发团队建议我们采用注解方式来配置事务。
但是目前在企业开发中,目前大部分项目使用的还是基于XML配置方式来使用事务,但是以后很多新项目也慢慢开始转向到了注解方式,这两种方式大家都需要去熟悉。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: