Spring学习笔记(3)(四)

2014-11-24 09:24:17 · 作者: · 浏览: 2

xsi:schemaLocation="http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"

2. 配置数据源

3. 配置dao和service Bean

4. 配置事务管理器DataSourceTransactionManager并注入其依赖的数据源

5. 配置事务切入点(配置哪些方法需要事务tx:method)

6. 配置切面并加入增强点(aop:config,aop:advisor)

propagation的取值:

REQUIRED(常用)业务方法需要在一个事务中运行。如果方法运行时,已经处在一个事务中,那么加入到该事务,否则为自己创建一个新的事务。

SUPPORTS(常用) 这一事务属性表明,如果业务方法在某个事务范围内被调用,则方法成为该事务的一部分。如果业务方法在事务范围外被调用,则方法在没有事务的环境下执行。

NOT_SUPPORTED 声明方法不需要事务。如果方法没有关联到一个事务,容器不会为它开启事务。如果方法在一个事务中被调用,该事务会被挂起,在方法调用结束后,原先的事务便会恢复执行。

REQUIRESNEW 属性表明不管是否存在事务,业务方法总会为自己发起一个新的事务。如果方法已经运行在一个事务中,则原有事务会被挂起,新的事务会被创建,直到方法执行结束,新事务才算结束,原先的事务才会恢复执行。

MANDATORY 该属性指定业务方法只能在一个已经存在的事务中执行,业务方法不能发起自己的事务。如果业务方法在没有事务的环境下调用,容器就会抛出例外。

Never 指定业务方法绝对不能在事务范围内执行。如果业务方法在某个事务中执行,容器会抛出例外,只有业务方法没有关联到任何事务,才能正常执行。

NESTED 如果一个活动的事务存在,则运行在一个嵌套的事务中. 如果没有活动事务, 则按REQUIRED属性执行.它使用了一个单独的事务,这个事务拥有多个可以回滚的保存点。内部事务的回滚不会对外部事务造成影响。它只对DataSourceTransactionManager事务管理器起效。

< xml version="1.0"encoding="UTF-8" >

xmlns:context="http://www.springframework.org/schema/context"

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-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

4.4基于注解配置的申明式事务
用到的注解:

@Transactional 该注解可以用于类或方法上,用于指明该类的所有方法或某个方法需要事务。

@Transactional//该类的所有方法都需要事务

publicclassTransferServiceImplAnno implements ITransferService {

@Override

publicvoid saveMoney(Stringname, Double money) {

//先判断账户是否存在

Accounta = accountDAO.get(name);

if(a != null) {

a.setBalance(a.getBalance()+ money);

accountDAO.update(a.getId(),a);//更新账户的钱

}else {

//否则新创建一个账户并将钱存进去

a= new Account(name, money);

accountDAO.save(a);

}

}

/**

* 给方法添加额外的事务配置,在方法中配置的事务优先执行

*/

@Transactional(propagation=Propagation.SUPPORTS,readOnly=true)

public AccountgetAccount(String name){

returnaccountDao.get(name);

}

}

配置文件:

< xml version="1.0"encoding="UTF-8" >

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-3.0.xsd

http://www.spri