---
title: "SPRING总结"
author: "qys2010"
date: "2011-02-26T22:52:08Z"
tags: ["DAO", "Hibernate", "Spring", "编程", "配置管理"]
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2011-02-26T22:52:08Z"
id: 932151
url: "https://qys2010.iteye.com/blog/932151"
---

Spring配置文件中关于事务配置总是由三个组成部分，分别是DataSource、TransactionManager和代理机制这三部分，无论哪种配置方式，一般变化的只是代理机制这部分。 DataSource、TransactionManager这两部分只是会根据数据访问方式有所变化，比如使用Hibernate进行数据访问时，DataSource实际为SessionFactory，TransactionManager的实现为HibernateTransactionManager。 根据代理机制的不同，总结了五种Spring事务的配置方式，配置文件如下： 第一种方式：每个Bean都有一个代理 PROPAGATION\_REQUIRED 第二种方式：所有Bean共享一个代理基类 PROPAGATION\_REQUIRED 第三种方式：使用拦截器 PROPAGATION\_REQUIRED \*Dao transactionInterceptor 第四种方式：使用tx标签配置的拦截器 第五种方式：全注解 此时在DAO上需加上@Transactional注解，如下： package com.bluesky.spring.dao; import java.util.List; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.stereotype.Component; import com.bluesky.spring.domain.User; @Transactional @Component("userDao") public class UserDaoImpl extends HibernateDaoSupport implements UserDao { public List listUsers() { return this.getSession().createQuery("from User").list(); } } Spring事务原理 统观spring事务，围绕着两个核心PlatformTransactionManager和TransactionStatus spring提供了几个关于事务处理的类： TransactionDefinition //事务属性定义 TranscationStatus //代表了当前的事务，可以提交，回滚。 PlatformTransactionManager这个是spring提供的用于管理事务的基础接口，其下有一个实现的抽象类AbstractPlatformTransactionManager,我们使用的事务管理类例如DataSourceTransactionManager等都是这个类的子类。 一般事务定义步骤： TransactionDefinition td = new TransactionDefinition(); TransactionStatus ts = transactionManager.getTransaction(td); try { //do sth transactionManager.commit(ts); } catch(Exception e){transactionManager.rollback(ts);} spring提供的事务管理可以分为两类：编程式的和声明式的。编程式的，比较灵活，但是代码量大，存在重复的代码比较多；声明式的比编程式的更灵活。 编程式主要使用transactionTemplate。省略了部分的提交，回滚，一系列的事务对象定义，需注入事务管理对象. void add() { transactionTemplate.execute( new TransactionCallback(){ pulic Object doInTransaction(TransactionStatus ts) { //do sth} } } 声明式： 使用TransactionProxyFactoryBean: PROPAGATION\_REQUIRED PROPAGATION\_REQUIRED PROPAGATION\_REQUIRED,readOnly 围绕Poxy的动态代理 能够自动的提交和回滚事务 org.springframework.transaction.interceptor. TransactionProxyFactoryBean ·PROPAGATION\_REQUIRED--支持当前事务，如果当前没有事务，就新建一个事务。这是最常见的选择。 ·PROPAGATION\_SUPPORTS--支持当前事务，如果当前没有事务，就以非事务方式执行。 ·PROPAGATION\_MANDATORY--支持当前事务，如果当前没有事务，就抛出异常。 ·PROPAGATION\_REQUIRES\_NEW--新建事务，如果当前存在事务，把当前事务挂起。 ·PROPAGATION\_NOT\_SUPPORTED--以非事务方式执行操作，如果当前存在事务，就把当前事务挂起。 ·PROPAGATION\_NEVER--以非事务方式执行，如果当前存在事务，则抛出异常。 ·PROPAGATION\_NESTED--如果当前存在事务，则在嵌套事务内执行。如果当前没有事务，则进行与PROPAGATION\_REQUIRED类似的操作。