spring(xml中的事务定义)

<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" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xsi:schemaLocation="
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

在早期版本的Spring中,声明事务需要装配一个TransactionProxyFactoryBean的特殊Bean。会导致冗长的配置文件。

spring现在提供了tx配置命名空间,极大简化spring中的声明式事务

要注意的是,aop命名空间也应该包括在内,因为有一些声明式事务配置元素依赖于部分spring的AOP配置元素

tx命名空间提供了一些新的xml配置元素,其中最值得注意的是<tx:advice>元素

当使用<tx:advice>来声明事务时,还需要一个事务管理器。根据规定优于配置,<tx:advice>假定事务管理器被声明为一个id为transactionManage的Bean.如果碰巧为事务管理器配置了不同id(如:txManage)则需要在transactionManage属性中明确指定:

	<!-- 定义事务处理方式 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="insert*" propagation="REQUIRED" />
			<tx:method name="ajax*" propagation="REQUIRED" />
			<tx:method name="query*" propagation="SUPPORTS" />
		</tx:attributes>
	</tx:advice>

但是<tx:advice>只是定义了AOP通知,但这只是事务通知,并不是完整的事务性切面,我们在<tx:advice>中没有声明哪些Bean应该被通知——所以需要一个切点来做这件事。

当然也可以不使用切点。

<tx:advice>配置元素极大地简化了spring声明式事务所需要的XML。但是还可以继续简化,tx命名空间还提供了<tx:annotation-driven>元素,通常只需要一行XML元素

<tx:annotation-driven  />最多在指定一下特定的事务管理器

<tx:annotation-driven transaction-manager="txManager"/>

<tx:annotation-driven  />元素告诉spring检查上下文中所有的Bean并查找使用@Transactional注解的Bean。

注意:对于每一个使用@Transactional注解的Bean,<tx:annotation-driven  />负责为它自动添加事务通知(<tx:attributes>)

通知的事务属性(<tx:method>)是通过@Transactional注解的参数来定义的

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

//在类级别上使用@Transactional注解,表示所有的方法都支持事务,并且是只读。

@Service("userService")

@Scope("prototype")

public class UserServiceImp implements UserService(){

 ...........

 @Transactional(propagation=Propagation.REQUIRED,readOnly=false)

/在方法级别上,注解标识这个方法所需要的事务上下文

public void addUser(User user){.......................}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值