栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

Spring Aop与声明式事务

Java 更新时间:发布时间: 百科书网 趣学号

1.对某实现BeanDefinition的对象,先实例化,后经过属性填充。

2.DefaultListableBeanFactory对象的initializeBean(...)方法中。

3.调用实现BeanPostProcessor接口的AnnotationAwareAspectJAutoProxyCreator类对象的postProcessAfterInitialization(...)

public class AnnotationAwareAspectJAutoProxyCreator {
    
    //解决代理对象的循环依赖
    //将其放入三级缓冲中,对某对象进行赋值操作后调用getEarlyBeanReference()
    //方法将代理对象提前暴露处理,等到该实例对象通过AnnotationAwareAspectJAutoProxyCreator类 
    //创建代理时,发现earlyProxyReferences存在对象名称,就直接返回代理对象 
    private final Set earlyProxyReferences;
    
    //存放代理对象的字节码
    private final Map> proxyTypes;
    
    //存放可以被代理的对象
    private final Map advisedBeans;


    //通过实例化对象创建代理对象
    public Object postProcessAfterInitialization() {
        if (bean != null) {
            Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
            
            //如果之前没有创建过该实例化对象,则调用wrapIfNecessary()方法创建
            //代理对象
            if (!this.earlyProxyReferences.contains(cacheKey)) {
                return this.wrapIfNecessary(bean, beanName, cacheKey)->{
                   //得到实例化bean的advices和Advisor
                   Object[] specificInterceptors = this.getAdvicesAndAdvisorsForBean(..);
                   
                   // specificInterceptors大于0,则创建代理对象,执行下面的语句
                   //存放可以能被代理的对象
                   this.advisedBeans.put(cacheKey, Boolean.TRUE);
                   //创建代理对象 
                   Object proxy = this.createProxy(specificInterceptors,...);
                    
                   //存放代理对象的字节码
                   this.proxyTypes.put(cacheKey, proxy.getClass());
                   
                   return proxy;
                }
                 
            }
        }

        return bean;
    }    

} 

4.在创建createProxy(specificInterceptors,...)方法中

  //创建proxyFactory,其属性
  // aopProxyFactory= new DefaultAopProxyFactory(); 根据该类创建代理对象。
  // targetSource 存放对象的实例(为属性赋值);
  // advisorChainFactory = new DefaultAdvisorChainFactory();
  // advisors 初始化Advisor
  //  1.@Aspect
  //    Advisor的实现类InstantiationModelAwarePointcutAdvisorImpl
  //                 其属性有pointcut,instantiatedAdvice有AspectJAfterThrowingAdvice
  //                 AspectJAfterReturningAdvice,AspectJAfterAdvice,AspectJAroundAdvice
  //                 AspectJMethodBeforeAdvice
  //    Advisor的实现类ExposeInvocationInterceptor 
  //                 其属性advice ExposeInvocationInterceptor 
  //  2.@Transactional 
  //    Advisor的实现类BeanFactoryTransactionAttributeSourceAdvisor
  //                  其属性pointcut, advice =TransactionInterceptor ,beanFactory        
  ProxyFactory proxyFactory = new ProxyFactory();

5.在执行方法时(Aspect拦截的方法),被CglibAopProxy$DynamicAdvisedInterceptor类的实例对象的intercept(...)方法拦截。

// CglibAopProxy$DynamicAdvisedInterceptor类的实例对象属性为
//     advised=ProxyFactory的实例对象

// 该方法得到advice
// ExposeInvocationInterceptor
// AspectJAfterThrowingAdvice
// AfterReturningAdviceInterceptor其属性advice=AspectJAfterReturningAdvice
// AspectJAfterAdvice
// AspectJAroundAdvice
// MethodBeforeAdviceInterceptor其属性advice=AspectJMethodBeforeAdvice

// 如果是@Transactional,则返回一个值chains=
//     TransactionInterceptor 其属性beanFactory,
//         其属性transactionAttributeSource对应的类AnnotationTransactionAttributeSource
List chains = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

//new CglibMethodInvocation对象,并调用其父类ReflectiveMethodInvocation的
//    proceed()方法作用currentInterceptorIndex加1,直到执行调用完 
//                                 interceptorsAndDynamicMethodMatchers中的advice。
//                                                     
// 该对象属性 interceptorsAndDynamicMethodMatchers 存放chains中的advice
//           currentInterceptorIndex = -1  初始-1,处理完一个advice,该值加1。
new CglibAopProxy.CglibMethodInvocation(...).proceed()->{

    //调用chains数组中对象的invoke(mi); 
    //mi为CglibAopProxy.CglibMethodInvocation对象
    // 第一个advice:ExposeInvocationInterceptor 属性ThreadLocal 
    //    invocation,目的将mi放到ThreadLocal中,通过ExposeInvocationInterceptor
    //  .invocation.get()
    ExposeInvocationInterceptor对象invoke(mi); 

    // ProceedingJoinPoint joinPoint为MethodInvocationProceedingJoinPoint对象
    //     其属性methodInvocation=为CglibAopProxy.CglibMethodInvocation对象
    //     其属性signature=为拦截的方法对象
    try {
        try {
            // 
            // 环绕方法执行joinPoint.proceed(); 实际就是将其属性
            // 的mi对象重新克隆出一个新的对象执行,currentInterceptorIndex加1
            AspectJAroundAdvice.invokeAdviceMethod(...)->{
                //这段代码时使用@Around下的方法的执行逻辑
                try {
                    1.执行joinPoint.proceed()前的逻辑 
                    2.joinPoint.proceed()->{
                    AspectJMethodBeforeAdvice.invokeAdviceMethod(...);
                    //拦截的方法体执行
                    this.invokeJoinpoint(); 
                    3.执行joinPoint.proceed()后的逻辑
                }catch(Exception e)
                    4.执行异常逻辑
                }finally{
                    5.执行最终逻辑
                }    
            }; 
        } finally {
            AspectJAfterAdvice.invokeAdviceMethod(...);
        }
        AspectJAfterReturningAdvice.afterReturning(...);
    }catch (Throwable var3) {     
       AspectJAfterThrowingAdvice.invokeAdviceMethod(...);
       throw var3;
    }
};

public class AspectJAfterThrowingAdvice {
    public Object invoke(MethodInvocation mi) throws Throwable {
        try {
            return mi.proceed();
        } catch (Throwable var3) {
            if (this.shouldInvokeOnThrowing(var3)) {
                this.invokeAdviceMethod(this.getJoinPointMatch(), (Object)null, var3);
            }

            throw var3;
        }
    }
}
public class AfterReturningAdviceInterceptor {
     public Object invoke(MethodInvocation mi) throws Throwable {
        Object retVal = mi.proceed();
        this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
        return retVal;
    }
}

public class AspectJAfterAdvice {
    public Object invoke(MethodInvocation mi) throws Throwable {
        Object var2;
        try {
            var2 = mi.proceed();
        } finally {
            this.invokeAdviceMethod(this.getJoinPointMatch(), (Object)null, (Throwable)null);
        }

        return var2;
    }
}

public class AspectJAroundAdvice {
    public Object invoke(MethodInvocation mi) throws Throwable {
        if (!(mi instanceof ProxyMethodInvocation)) {
            throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi);
        } else {
            ProxyMethodInvocation pmi = (ProxyMethodInvocation)mi;
            ProceedingJoinPoint pjp = this.lazyGetProceedingJoinPoint(pmi);
            JoinPointMatch jpm = this.getJoinPointMatch(pmi);
            return this.invokeAdviceMethod(pjp, jpm, (Object)null, (Throwable)null);
        }
    }
}

public class MethodBeforeAdviceInterceptor {
    public Object invoke(MethodInvocation mi) throws Throwable {
        this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
        return mi.proceed();
    }
} 

6.在执行方法时(@Transactional方法),被CglibAopProxy$DynamicAdvisedInterceptor类的实例对象的intercept(...)方法拦截。

//new CglibAopProxy.CglibMethodInvocation(...).proceed()
// 遍历执行interceptorsAndDynamicMethodMatchers
public class TransactionInterceptor {
    
    public Object invoke(MethodInvocation invocation)->{
            
            //其父类TransactionAspectSupport的方法
            this.invokeWithinTransaction()->{
                
                //DataSourceTransactionManager对象.doBegin() 
                //con.setAutoCommit(false);
                TransactionAspectSupport.TransactionInfo txInfo = 
                this.createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
                result = null;

                try {
                    //执行方法体
                    result = invocation.proceedWithInvocation();
                } catch (Throwable var17) {
                    //回滚
                    this.completeTransactionAfterThrowing(txInfo, var17);
                    throw var17;
                } finally {
                    //清除ThreadLocal 
                    //    transactionInfoHolder
                    this.cleanupTransactionInfo(txInfo);
                }
            
                //提交事务
                this.commitTransactionAfterReturning(txInfo);
                return result;
        }
    }
}
// 主要接口方法 Pointcut getPointcut()/getAdvice()
public class BeanFactoryTransactionAttributeSourceAdvisor {
    
    // 值为AnnotationTransactionAttributeSource对象
    private TransactionAttributeSource transactionAttributeSource;
    
    // 值为DefaultListableBeanFactory
    private BeanFactory beanFactory;
    
    // 值TransactionInterceptor对象t
    // 如果该对象t中的 PlatformTransactionManager transactionManager为null,则从对象t的 
    //    transactionManagerCache.get(DEFAULT_TRANSACTION_MANAGER_KEY)
    // 如果为null,则beanFactory中得到DataSourceTransactionManager对象,并放入
    // transactionManagerCache中key为DEFAULT_TRANSACTION_MANAGER_KEY
    
    // 用ProxyFactory对象的方法getInterceptorsAndDynamicInterceptionAdvice(
    //    method,targetClass)得到TransactionInterceptor对象
    // 使用TransactionInterceptor对象.invokeWithinTransaction(...)
    private transient volatile Advice advice;


}



//spring事务注解属性资源
public class AnnotationTransactionAttributeSource{
    //解析公共方法
    private final boolean publicMethodsOnly = true;
     
    //值为SpringTransactionAnnotationParser
    //SpringTransactionAnnotationParser.parseTransactionAnnotation(AnnotatedElement ae)
    //方法: 解析类方法上的@Transaction的属性赋值给RuleBasedTransactionAttribute对象
    private final Set annotationParsers;
    
    //储存带有@Transaction注解方法
    // key MethodClassKey类 
    // value DefaultTransactionAttribute=PROPAGATION_REQUIRED,ISOLATION_DEFAULT
    //       RuleBasedTransactionAttribute
    private final Map attributeCache;

}

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 = 1;
    int ISOLATION_READ_COMMITTED = 2;
    int ISOLATION_REPEATABLE_READ = 4;
    int ISOLATION_SERIALIZABLE = 8;
    int TIMEOUT_DEFAULT = -1;
}

TransactionAspectSupport.TransactionInfo  其属性
transactionManager=DataSourceTransactionManager对象
transactionAttribute=PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
joinpointIdentification=org.sang.security01.OrderService.setOrder某方法
transactionStatus=DefaultTransactionStatus对象
this$0=TransactionInterceptor对象


转载请注明:文章转载自 www.051e.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号