Spring的两种事务配置

来源:互联网 发布:好视通视频会议软件 编辑:程序博客网 时间:2024/05/20 13:07

 

1.编程式事务管理,用注解配置,可以提高项目开发的效率,但是耦合性大大的提高。

@Component
@Aspect
public class TxInterceptor {
 private SessionFactory sessionFactory = null;

 @Autowired
 public void setSessionFactory(SessionFactory sessionFactory) {
  this.sessionFactory = sessionFactory;
 }
 @SuppressWarnings("unused")
 @Pointcut("execution(public * com.accp.biz.impl.*.*(..))")
 private void anlyTx() {
 }

 @Before("anlyTx()")
 public void beginTx() {
  sessionFactory.getCurrentSession().beginTransaction();

 }
 @After("anlyTx()")
 // 织入语法
 public void commitTx() {
  sessionFactory.getCurrentSession().beginTransaction().commit();
 }

 @AfterThrowing(throwing = "HibernateException", value = "execution(public * com.accp.biz.impl.*.*(..))")
 public void roolBackTx() {

  sessionFactory.getCurrentSession().beginTransaction().rollback();
 }
}

 

在applicationcontext.xml中需要配置

<--将被注解类的对象交给Spring的IoC容器进行管理 -->

<context:annotation-config/>
<!-- 管理被注解的包 -->
<context:component-scan base-package="com.accp"/>
<!-- 为切面自动生成代理(将切面中的横切关注功能通过代理对象加到指定的位置) -->
<aop:aspectj-autoproxy/>

 

2.声明式事务管理,虽然写配置比较恶心,但是低耦合,且有助于你在修改项目的时候,只需要改配置文件

 

<!--使用tx标签配置的拦截器, 定义事务管理器(声明式的事务) -->
 <bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>
 <!-- txAdvice事务通知 -->
 <tx:advice id="txAdvice" transaction-manager="transactionManager">
  <tx:attributes>
     <tx:method name="get*" read-only= "true" />
     <tx:method name="find*" read-only="true"/>
     <tx:method name="search*" read-only="true"/>
     <tx:method name="query*" read-only="true"/>
    <!-- 事务的传播级别 -->
     <tx:method name="add*" propagation="REQUIRED"/>
     <tx:method name="del*" propagation="REQUIRED"/>
     <tx:method name="update*" propagation="REQUIRED"/>
     <tx:method name="do*" propagation="REQUIRED"/>
   <tx:method name="*" propagation="REQUIRED"  read-only="true" />
  </tx:attributes>
 </tx:advice>

 <aop:config>
  <aop:pointcut id="interceptorPointCuts"
   expression="execution(public * com.accp.biz.impl.*.*(..))" />
  <aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" />
 </aop:config>
 

 

原创粉丝点击