spring中如何将事务添加到切面中

来源:互联网 发布:收货人 余杭嘉云淘宝 编辑:程序博客网 时间:2024/05/17 08:29

头部信息:

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"></beans>

<!-- 声明式事务 --><bean name="txmanager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"><!-- 事务开启必须使用session --><property name="sessionFactory" ref="sessionFactory"></property></bean><!-- 事务增强类 transaction-manager:这种机制要放到上面哪一个bean中,transaction-manager如果不写有一个默认值transactionManager,此时必须保证声明式事务中的bean的名字是transactionManager--><tx:advice id="txAdvice" transaction-manager="txmanager"><tx:attributes><!-- REQUIRED: 第一种事务声明方式,需要事务SUPPORTS:第四种声明方式,不需要事务--><tx:method name="save*" propagation="REQUIRED"/><tx:method name="update*" propagation="REQUIRED"/><tx:method name="delete*" propagation="REQUIRED"/><tx:method name="get*" propagation="SUPPORTS"/><tx:method name="find*" propagation="SUPPORTS"/><!-- 匹配以上之外的所有方法,类似于switch的default --><tx:method name="*" propagation="SUPPORTS"/></tx:attributes></tx:advice><!-- 使用AOP切面,开始把事务添加到切面中 --><aop:config><!-- 表达式:返回类型模式是*,它代表了匹配任意的返回类型应用到service下所有实现类的所有类的所有方法所有参数 --><aop:pointcut expression="execution(* com.bdqn.ssh.service.impl.*.* (..))" id="mypoint"/><!-- 织入 把管理类[txmanager]生成的代理[txAdvice],织入到所定义的切面[mypoint]中 --><aop:advisor advice-ref="txAdvice" pointcut-ref="mypoint"/></aop:config>

Spring AOP 用户可能会经常使用 execution切入点指示符。执行表达式的格式如下:
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern)  throws-pattern?)
除了返回类型模式(上面代码片断中的ret-type-pattern),名字模式和参数模式以外, 所有的部分都是可选的。
你会使用的最频繁的返回类型模式是*,它代表了匹配任意的返回类型。 
 一个全限定的类型名将只会匹配返回给定类型的方法。名字模式匹配的是方法名。 你可以使用*通配符作为所有或者部分命名模式。
参数模式稍微有点复杂:()匹配了一个不接受任何参数的方法, 而(..)匹配了一个接受任意数量参数的方法(零或者更多)。
 模式(*)匹配了一个接受一个任何类型的参数的方法。
AccountService接口定义的任意方法的执行:
execution(* com.bdqn.service.AccountService.impl.*.* (..))//匹配该接口下的所有类所有方法所有参数