- 浏览: 20768 次
- 性别:
- 来自: 遂宁
最新评论
-
momantang:
mark too
common-fileupload 分析 -
jk8341444:
写的一点思路没有
common-fileupload 分析 -
loocao:
mark...
common-fileupload 分析
先主要介绍几个核心类
PlatformTransactionManager(平台事务管理)
TransactionStatus(事务状态)
TransactionDefinition(事务的级别和传播方式)
整个PlatformTransactionManager接口提供了一下3个方法
public interface TransactionStatus extends SavepointManager { boolean isNewTransaction(); boolean hasSavepoint(); void setRollbackOnly(); boolean isRollbackOnly(); boolean isCompleted(); }
public interface TransactionDefinition { int PROPAGATION_REQUIRED = 0;//支持现有事务。如果没有则创建一个事务 int PROPAGATION_SUPPORTS = 1;//支持现有事务。如果没有则以非事务状态运行。 int PROPAGATION_MANDATORY = 2;//支持现有事务。如果没有则抛出异常。 int PROPAGATION_REQUIRES_NEW = 3;//总是发起一个新事务。如果当前已存在一个事务,则将其挂起。 int PROPAGATION_NOT_SUPPORTED = 4;//不支持事务,总是以非事务状态运行,如果当前存在一个事务,则将其挂起。 int PROPAGATION_NEVER = 5;//不支持事务,总是以非事务状态运行,如果当前存在一个事务,则抛出异常。 int PROPAGATION_NESTED = 6;//如果当前已经存在一个事务,则以嵌套事务的方式运行,如果当前没有事务,则以默认方式(第一个)执行 int ISOLATION_DEFAULT = -1;//默认隔离等级 int ISOLATION_READ_UNCOMMITTED = Connection.TRANSACTION_READ_UNCOMMITTED;//最低隔离等级,仅仅保证了读取过程中不会读取到非法数据 int ISOLATION_READ_COMMITTED = Connection.TRANSACTION_READ_COMMITTED;//某些数据库的默认隔离等级;保证了一个事务不会读到另外一个并行事务已修改但未提交的数据 int ISOLATION_REPEATABLE_READ = Connection.TRANSACTION_REPEATABLE_READ;//比上一个更加严格的隔离等级。保证了一个事务不会修改已经由另一个事务读取但未提交(回滚)的数据 int ISOLATION_SERIALIZABLE = Connection.TRANSACTION_SERIALIZABLE;//性能代价最为昂贵,最可靠的隔离等级。所有事务都严格隔离,可视为各事务顺序执 int TIMEOUT_DEFAULT = -1; int getPropagationBehavior(); int getIsolationLevel(); int getTimeout(); boolean isReadOnly(); String getName(); }
HibernateTransactionObject
此类具有以下3个常用参数
private SessionHolder sessionHolder;
private boolean newSessionHolder;
private boolean newSession;
SessionHolder
是spring定义的一个类,将事务和session包装在一起
private static final Object DEFAULT_KEY = new Object();
private final Map sessionMap = Collections.synchronizedMap(new HashMap(1));
private Transaction transaction;
private FlushMode previousFlushMode;
下面将大致讲讲以拦击器管理事务的方式
<bean id="proxyFactory" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>businessOrderDao</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>transactionInterceptor</value>
</list>
</property>
</bean>
Spring的事务配置方式之一 :使用拦截器
List<GpBusiOrderInfo> all = businessOrderDao.queryAndUpdateGpBusiOrderInfo());
当程序进入这个方法的时候,其实是进入的spring的一个代理中
JdkDynamicAopProxy
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
MethodInvocation invocation = null;
Object oldProxy = null;
boolean setProxyContext = false;
TargetSource targetSource = this.advised.targetSource;
//此处targetSource 的值 =SingletonTargetSource for target object[com.wasu.hestia.orm.dao.hibernate.BusinessOrderInfoDaoImpl@1f0d7f5]
// Class targetClass = null;
// Object target = null;
try {
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// The target does not implement the equals(Object) method itself.
return (equals(args[0]) ? Boolean.TRUE : Boolean.FALSE);
}
if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// The target does not implement the hashCode() method itself.
return new Integer(hashCode());
}
if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
method.getDeclaringClass().isAssignableFrom(Advised.class)) {
// Service invocations on ProxyConfig with the proxy config...
return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
}
Object retVal = null;
if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
// May be <code>null</code>. Get as late as possible to minimize the time we "own" the target,
// in case it comes from a pool.
target = targetSource.getTarget();
if (target != null) {
targetClass = target.getClass();
}
// Get the interception chain for this method.
List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
// getInterceptorsAndDynamicInterceptionAdvice 是根据方法和被代理的目标类来获取配置文件中对其进行拦截的操作,在这里只有org.springframework.transaction.interceptor.TransactionInterceptor//@1b1deea]
// Check whether we have any advice. If we don't, we can fallback on direct
// reflective invocation of the target, and avoid creating a MethodInvocation.
if (chain.isEmpty()) {
// We can skip creating a MethodInvocation: just invoke the target directly
// Note that the final invoker must be an InvokerInterceptor so we know it does
// nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, args);
}
else {
// We need to create a method invocation...
invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
这个new了一个ReflectiveMethodInvocation对象,他的基类就是MethodInvocation
// Proceed to the joinpoint through the interceptor chain.
retVal = invocation.proceed();
//此方法参见下面 1
}
// Massage return value if necessary.
if (retVal != null && retVal == target && method.getReturnType().isInstance(proxy) &&
!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
// Special case: it returned "this" and the return type of the method
// is type-compatible. Note that we can't help if the target sets
// a reference to itself in another returned object.
retVal = proxy;
}
return retVal;
}
finally {
if (target != null && !targetSource.isStatic()) {
// Must have come from TargetSource.
targetSource.releaseTarget(target);
}
if (setProxyContext) {
// Restore old proxy.
AopContext.setCurrentProxy(oldProxy);
}
}
}
1.
public Object proceed() throws Throwable {
// We start with an index of -1 and increment early.
// currentInterceptorIndex的初始化值为-1,在这里也就是判断是否还有拦截器需要执行
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint();
}
//此出当前currentInterceptorIndex+1的下标的拦截器取出,当前程序是0,对应的拦截器是org.springframework.transaction.interceptor.TransactionInterceptor@1b1deea
Object interceptorOrInterceptionAdvice = this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
//这里返回false
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
// Evaluate dynamic method matcher here: static part will already have
// been evaluated and found to match.
InterceptorAndDynamicMethodMatcher dm =
(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
return dm.interceptor.invoke(this);
}
else {
// Dynamic matching failed.
// Skip this interceptor and invoke the next in the chain.
return proceed();
}
}
else {
// It's an interceptor, so we just invoke it: The pointcut will have
// been evaluated statically before this object was constructed.
//由于interceptorOrInterceptionAdvice现在是Object类型,所以需要将当前的interceptorOrInterceptionAdvice转换成MethodInterceptor也就是TransactionInterceptor的基类
请参看2
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
2.
程序进入了TransactionInterceptor,调用它的invoke方法
public Object invoke(final MethodInvocation invocation) throws Throwable {
// Work out the target class: may be <code>null</code>.
// The TransactionAttributeSource should be passed the target class
// as well as the method, which may be from an interface.
//当前的targetClass 就是com.wasu.hestia.orm.dao.hibernate.BusinessOrderInfoDaoImpl
Class targetClass = (invocation.getThis() != null ? invocation.getThis().getClass() : null);
// If the transaction attribute is null, the method is non-transactional.
//根据方法名和目标对象获取TransactionAttribute的属性,此处值为PROPAGATION_REQUIRED,ISOLATION_DEFAULT,其中ISOLATION_DEFAULT是默认的数据库隔离级别
final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(invocation.getMethod(), targetClass);
// joinpointIdentification 的值为com.wasu.hestia.orm.dao.BusinessOrderInfoDao.queryAndUpdateGpBusiOrderInfo
final String joinpointIdentification = methodIdentification(invocation.getMethod());
if (txAttr == null || !(getTransactionManager() instanceof CallbackPreferringPlatformTransactionManager)) {
// Standard transaction demarcation with getTransaction and commit/rollback calls.
// createTransactionIfNecessary 参见3
TransactionInfo txInfo = createTransactionIfNecessary(txAttr, joinpointIdentification);
Object retVal = null;
try {
// This is an around advice: Invoke the next interceptor in the chain.
// This will normally result in a target object being invoked.
retVal = invocation.proceed();
}
catch (Throwable ex) {
// target invocation exception
completeTransactionAfterThrowing(txInfo, ex);
throw ex;
}
finally {
cleanupTransactionInfo(txInfo);
}
commitTransactionAfterReturning(txInfo);
return retVal;
}
else {
// It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in.
try {
Object result = ((CallbackPreferringPlatformTransactionManager) getTransactionManager()).execute(txAttr,
new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
TransactionInfo txInfo = prepareTransactionInfo(txAttr, joinpointIdentification, status);
try {
return invocation.proceed();
}
catch (Throwable ex) {
if (txAttr.rollbackOn(ex)) {
// A RuntimeException: will lead to a rollback.
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
else {
throw new ThrowableHolderException(ex);
}
}
else {
// A normal return value: will lead to a commit.
return new ThrowableHolder(ex);
}
}
finally {
cleanupTransactionInfo(txInfo);
}
}
});
// Check result: It might indicate a Throwable to rethrow.
if (result instanceof ThrowableHolder) {
throw ((ThrowableHolder) result).getThrowable();
}
else {
return result;
}
}
catch (ThrowableHolderException ex) {
throw ex.getCause();
}
}
}
3. TransactionAspectSupport的createTransactionIfNecessary方法
protected TransactionInfo createTransactionIfNecessary(
TransactionAttribute txAttr, final String joinpointIdentification) {
// If no name specified, apply method identification as transaction name.
if (txAttr != null && txAttr.getName() == null) {
txAttr = new DelegatingTransactionAttribute(txAttr) {
public String getName() {
return joinpointIdentification;
}
};
}
TransactionStatus status = null;
if (txAttr != null) {
//此处获取你的平台事务,我们这里是HiberanteTransactionManager
PlatformTransactionManager tm = getTransactionManager();
if (tm != null) {
//此处开始获取事务,里面的一些列动作都相当重要,开发中很多的错误信息都是从这个里面报出来的
参见4
status = tm.getTransaction(txAttr);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Skipping transactional joinpoint [" + joinpointIdentification +
"] because no transaction manager has been configured");
}
}
}
return prepareTransactionInfo(txAttr, joinpointIdentification, status);
}
4.
AbstractPlatformTransactionManager
public final TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
//取到一个事务对象,参看5
Object transaction = doGetTransaction();
// Cache debug flag to avoid repeated checks.
boolean debugEnabled = logger.isDebugEnabled();
if (definition == null) {
// Use defaults if no transaction definition given.
definition = new DefaultTransactionDefinition();
}
//判断当前transaction对象中是否真正存在事务了,底层的判断其实就是判断当前transaction中是否SessionHolder为null, SessionHolder中的transaction属性是否为null,SessionHolder中的session属性的transaction属性是否为null,此处以为false
if (isExistingTransaction(transaction)) {
// Existing transaction found -> check propagation behavior to find out how to behave.
return handleExistingTransaction(definition, transaction, debugEnabled);
}
// Check definition settings for new transaction.
if (definition.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
throw new InvalidTimeoutException("Invalid transaction timeout", definition.getTimeout());
}
// No existing transaction found -> check propagation behavior to find out how to proceed.
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
throw new IllegalTransactionStateException(
"No existing transaction found for transaction marked with propagation 'mandatory'");
}
else if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||
definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||
definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
SuspendedResourcesHolder suspendedResources = suspend(null);
if (debugEnabled) {
logger.debug("Creating new transaction with name [" + definition.getName() + "]: " + definition);
}
try {
//此处就是传说中的真正事务和Session的操作入口
参见 6
doBegin(transaction, definition);
}
catch (RuntimeException ex) {
resume(null, suspendedResources);
throw ex;
}
catch (Error err) {
resume(null, suspendedResources);
throw err;
}
boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
return newTransactionStatus(
definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
}
else {
// Create "empty" transaction: no actual transaction, but potentially synchronization.
boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
return newTransactionStatus(definition, null, true, newSynchronization, debugEnabled, null);
}
}
5.
HibernateTransactionManager
protected Object doGetTransaction() {
// HibernateTransactionObject参见前面的类说明
HibernateTransactionObject txObject = new HibernateTransactionObject();
txObject.setSavepointAllowed(isNestedTransactionAllowed());
//此方法是取出与当前线程绑定SessionHolder,此处取出为null
SessionHolder sessionHolder =
(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
if (sessionHolder != null) {
if (logger.isDebugEnabled()) {
logger.debug("Found thread-bound Session [" +
SessionFactoryUtils.toString(sessionHolder.getSession()) + "] for Hibernate transaction");
}
txObject.setSessionHolder(sessionHolder);
}
else if (this.hibernateManagedSession) {
try {
Session session = getSessionFactory().getCurrentSession();
if (logger.isDebugEnabled()) {
logger.debug("Found Hibernate-managed Session [" +
SessionFactoryUtils.toString(session) + "] for Spring-managed transaction");
}
txObject.setExistingSession(session);
}
catch (HibernateException ex) {
throw new DataAccessResourceFailureException(
"Could not obtain Hibernate-managed Session for Spring-managed transaction", ex);
}
}
if (getDataSource() != null) {
//此处取出与当前线程绑定的ConnectionHolder,此处为null
ConnectionHolder conHolder = (ConnectionHolder)
TransactionSynchronizationManager.getResource(getDataSource());
txObject.setConnectionHolder(conHolder);
}
return txObject;
}
6.
protected void doBegin(Object transaction, TransactionDefinition definition) { HibernateTransactionObject txObject = (HibernateTransactionObject) transaction; if (txObject.hasConnectionHolder() && !txObject.getConnectionHolder().isSynchronizedWithTransaction()) { throw new IllegalTransactionStateException( "Pre-bound JDBC Connection found! HibernateTransactionManager does not support " + "running within DataSourceTransactionManager if told to manage the DataSource itself. " + "It is recommended to use a single HibernateTransactionManager for all transactions " + "on a single DataSource, no matter whether Hibernate or JDBC access."); } Session session = null; try { if (txObject.getSessionHolder() == null || txObject.getSessionHolder().isSynchronizedWithTransaction()) { //此处可以获取注入的Hibernate的实体拦截器 Interceptor entityInterceptor = getEntityInterceptor(); //在此处获取了一个session Session newSession = (entityInterceptor != null ? getSessionFactory().openSession(entityInterceptor) : getSessionFactory().openSession()); if (logger.isDebugEnabled()) { logger.debug("Opened new Session [" + SessionFactoryUtils.toString(newSession) + "] for Hibernate transaction"); } //将session放入txObject中,此处的实际操作是 public void setSession(Session session) { this.sessionHolder = new SessionHolder(session); this.newSessionHolder = true; this.newSession = true; } txObject.setSession(newSession); } session = txObject.getSessionHolder().getSession(); if (this.prepareConnection && isSameConnectionForEntireSession(session)) { // We're allowed to change the transaction settings of the JDBC Connection. if (logger.isDebugEnabled()) { logger.debug( "Preparing JDBC Connection of Hibernate Session [" + SessionFactoryUtils.toString(session) + "]"); } Connection con = session.connection(); Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition); txObject.setPreviousIsolationLevel(previousIsolationLevel); } else { // Not allowed to change the transaction settings of the JDBC Connection. if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) { // We should set a specific isolation level but are not allowed to... throw new InvalidIsolationLevelException( "HibernateTransactionManager is not allowed to support custom isolation levels: " + "make sure that its 'prepareConnection' flag is on (the default) and that the " + "Hibernate connection release mode is set to 'on_close' (SpringTransactionFactory's default). " + "Make sure that your LocalSessionFactoryBean actually uses SpringTransactionFactory: Your " + "Hibernate properties should *not* include a 'hibernate.transaction.factory_class' property!"); } if (logger.isDebugEnabled()) { logger.debug( "Not preparing JDBC Connection of Hibernate Session [" + SessionFactoryUtils.toString(session) + "]"); } } //如果事务级别是readOnly就会将session的FlushMode设置NEVER if (definition.isReadOnly() && txObject.isNewSession()) { // Just set to NEVER in case of a new Session for this transaction. session.setFlushMode(FlushMode.NEVER); } if (!definition.isReadOnly() && !txObject.isNewSession()) { // We need AUTO or COMMIT for a non-read-only transaction. FlushMode flushMode = session.getFlushMode(); if (flushMode.lessThan(FlushMode.COMMIT)) { session.setFlushMode(FlushMode.AUTO); txObject.getSessionHolder().setPreviousFlushMode(flushMode); } } Transaction hibTx = null; // Register transaction timeout. int timeout = determineTimeout(definition); if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) { // Use Hibernate's own transaction timeout mechanism on Hibernate 3.1 // Applies to all statements, also to inserts, updates and deletes! hibTx = session.getTransaction(); hibTx.setTimeout(timeout); hibTx.begin(); } else { // Open a plain Hibernate transaction without specified timeout. //传说中真正的获取到一个transaction hibTx = session.beginTransaction(); } // Add the Hibernate transaction to the session holder. //将这个事务放入SessionHolder中 txObject.getSessionHolder().setTransaction(hibTx); // Register the Hibernate Session's JDBC Connection for the DataSource, if set. if (getDataSource() != null) { Connection con = session.connection(); ConnectionHolder conHolder = new ConnectionHolder(con); if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) { conHolder.setTimeoutInSeconds(timeout); } if (logger.isDebugEnabled()) { logger.debug("Exposing Hibernate transaction as JDBC transaction [" + con + "]"); } TransactionSynchronizationManager.bindResource(getDataSource(), conHolder); txObject.setConnectionHolder(conHolder); } // Bind the session holder to the thread. if (txObject.isNewSessionHolder()) { //将当前线程与SessionHolder绑定 TransactionSynchronizationManager.bindResource(getSessionFactory(), txObject.getSessionHolder()); } txObject.getSessionHolder().setSynchronizedWithTransaction(true); } catch (Exception ex) { if (txObject.isNewSession()) { try { if (session.getTransaction().isActive()) { session.getTransaction().rollback(); } } catch (Throwable ex2) { logger.debug("Could not rollback Session after failed transaction begin", ex); } finally { SessionFactoryUtils.closeSession(session); } } throw new CannotCreateTransactionException("Could not open Hibernate Session for transaction", ex); } }
相关推荐
spring事务分析spring事务分析spring事务分析
Spring源代码分析(三):Spring JDBC Spring源代码解析(四):Spring MVC Spring源代码解析(五):Spring AOP获取Proxy Spring源代码解析(六):Spring声明式事务处理 Spring源代码解析(七):Spring AOP中对拦截器...
包含spring事务管理案例的项目源码和说明文档
spring的核心就是IC依赖注入,那么就要先解析依赖配置,然后再注入。所以spring的功能都会出现两块,一块是解析mxl,一块是构建BeanDefinition。...事务增强器也是这样,先要解析事务的标签,然后才是执行事务。
本文处理spring+mybatis,或springjdbc,对oracle事务不能提交的问题分析与解决
Spring框架的事务管理应用分析.doc
jdbc+spring+mysql事务理解和分析
全面分析_Spring_的编程式事务管理及声明式事务管理,本教程假定您已经掌握了 Java 基础知识,并对 Spring 有一定了解。您还需要具备基本的事务管理的知识,比如:事务的定义,隔离级别的概念,等等。本文将直接使用...
spring事务_案例_PPT 一、事务传播机制的demo案例,内容包括: 1.业务代码列举7种事务传播机制的情况,每个测试方法都附带日志分析记录、使用场景和实际场景,小白也能看得懂!!! 2.在测试类Test包下,使用juniter...
Spring 的事务管理是 Spring 框架中一个比较重要的知识点,该知识点本身并不复杂,只是由于其比较灵活,导致初学者很难把握。本教程从基础知识开始,详细分析了 Spring 事务管理的使用方法,为读者理清思路。
此外,Spring事务管理器支持多种类型的事务策略,包括不同的传播行为和隔离级别,允许开发者根据具体业务场景选择最合适的事务管理策略。深入理解Spring声明式事务的工作原理,不仅能帮助开发者更高效地使用Spring...
Spring Boot实战与原理分析视频课程包含14-18,本视频教程为网络整理,如有侵权,请联系删除。谢谢 Spring Boot实战与原理分析视频课程 课程目录: 1 Spring Boot概述与课程概要介绍20:33 2 Spring4 快速入门59:56...
1.Spring源代码解析(一):Spring中的事务处理 2. Spring源代码解析(二):ioc容器在Web容器中的启动 3.Spring源代码解析(三):Spring JDBC 4.Spring源代码解析(四):Spring MVC 5.Spring源代码解析(五):Spring ...
Spring,Bean调用,事务,AOP,配置详细说明 提升开发效率
NULL 博文链接:https://konglx.iteye.com/blog/1836826
spring事务管理中xml的分析
主要介绍了Spring事务失效问题分析及解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
全面分析_Spring_的编程式事务管理及声明式事务管理.