1. 代理对象创建

1.1 AOP基础⽤例准备

1.1.1 Bean定义

  1. @Component
  2. public class LagouBean {
  3. public void tech(){
  4. System.out.println("java learning......");
  5. }
  6. }

1.1.2 Aspect定义

  1. package com.lagou;
  2. import org.aspectj.lang.annotation.Aspect;
  3. import org.aspectj.lang.annotation.Before;
  4. import org.aspectj.lang.annotation.Pointcut;
  5. import org.springframework.stereotype.Component;
  6. @Component
  7. @Aspect
  8. public class LagouAspect {
  9. @Pointcut("execution(* com.lagou.*.*(..))")
  10. public void pointcut(){
  11. }
  12. @Before("pointcut()")
  13. public void before() {
  14. System.out.println("before method ......");
  15. }
  16. }

1.1.3 测试⽤例

  1. /**
  2. * 测试⽤例:Aop 代理对象创建
  3. */
  4. @Test
  5. public void testAopProxyBuild(){
  6. ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
  7. LagouBean lagouBean = applicationContext.getBean(LagouBean.class);
  8. lagouBean.tech();
  9. }

1.2 时机点分析

image.png
我们发现在 getBean 之前,LagouBean对象已经产⽣(即在第⼀⾏初始化代码中完成),⽽且该对象是⼀个代理对象(Cglib代理对象),我们断定,容器初始化过程中⽬标Ban已经完成了代理,返回了代理对象。

1.3 代理对象创建流程

AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition)

  1. /**
  2. *
  3. * 初始化Bean
  4. 包括Bean后置处理器初始化
  5. Bean的⼀些初始化⽅法的执⾏init-method
  6. Bean的实现的声明周期相关接⼝的属性注⼊
  7. */
  8. protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
  9. // 执⾏所有的AwareMethods
  10. if (System.getSecurityManager() != null) {
  11. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {invokeAwareMethods(beanName, bean);
  12. return null;
  13. }, getAccessControlContext());
  14. }
  15. else {
  16. invokeAwareMethods(beanName, bean);
  17. }
  18. Object wrappedBean = bean;
  19. if (mbd == null || !mbd.isSynthetic()) {
  20. // 执⾏所有的BeanPostProcessor#postProcessBeforeInitialization 初始化之前的处理器⽅法
  21. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  22. }
  23. try {
  24. // 这⾥就开始执⾏afterPropertiesSet(实现了InitializingBean接⼝)⽅法和initMethod
  25. invokeInitMethods(beanName, wrappedBean, mbd);
  26. }
  27. catch (Throwable ex) {
  28. throw new BeanCreationException((mbd != null ? mbd.getResourceDescription() : null), beanName, "Invocation of init method failed", ex);
  29. }
  30. if (mbd == null || !mbd.isSynthetic()) {
  31. // 整个Bean初始化完成,执⾏后置处理器⽅法
  32. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  33. }
  34. return wrappedBean;
  35. }

AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization

  1. @Override
  2. public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
  3. Object result = existingBean;
  4. // 循环执⾏后置处理器
  5. for (BeanPostProcessor processor : getBeanPostProcessors()) {
  6. Object current = processor.postProcessAfterInitialization(result,beanName);
  7. if (current == null) {
  8. return result;
  9. }
  10. result = current;
  11. }
  12. return result;
  13. }

image.png
创建代理对象的后置处理器AbstractAutoProxyCreator#postProcessAfterInitialization

  1. /**
  2. * Create a proxy with the configured interceptors if the bean is
  3. * identified as one to proxy by the subclass.
  4. * @see #getAdvicesAndAdvisorsForBean
  5. */
  6. @Override
  7. public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
  8. if (bean != null) {
  9. // 检查下该类是否已经暴露过了(可能已经创建了,⽐如A依赖B时,创建A时候,就会先去创建B。
  10. // 当真正需要创建B时,就没必要再代理⼀次已经代理过的对象),避免重复创建
  11. Object cacheKey = getCacheKey(bean.getClass(), beanName);
  12. if (this.earlyProxyReferences.remove(cacheKey) != bean) {
  13. return wrapIfNecessary(bean, beanName, cacheKey);
  14. }
  15. }
  16. return bean;
  17. }

AbstractAutoProxyCreator#wrapIfNecessary

  1. /**
  2. * Wrap the given bean if necessary, i.e. if it is eligible for being
  3. proxied.
  4. * @param bean the raw bean instance
  5. * @param beanName the name of the bean
  6. * @param cacheKey the cache key for metadata access
  7. * @return a proxy wrapping the bean, or the raw bean instance as-is
  8. */
  9. protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
  10. // targetSourcedBeans包含,说明前⾯创建过
  11. if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
  12. return bean;
  13. }
  14. if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
  15. return bean;
  16. }
  17. if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
  18. this.advisedBeans.put(cacheKey, Boolean.FALSE);
  19. return bean;
  20. }
  21. // Create proxy if we have advice.
  22. // 得到所有候选Advisor,对Advisors和bean的⽅法双层遍历匹配,最终得到⼀个List<Advisor>,即specificInterceptors
  23. Object[] specificInterceptors =
  24. getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
  25. if (specificInterceptors != DO_NOT_PROXY) {
  26. this.advisedBeans.put(cacheKey, Boolean.TRUE);
  27. // 重点,创建代理对象
  28. Object proxy = createProxy(
  29. bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
  30. this.proxyTypes.put(cacheKey, proxy.getClass());
  31. return proxy;
  32. }
  33. this.advisedBeans.put(cacheKey, Boolean.FALSE);
  34. return bean;
  35. }

AbstractAutoProxyCreator#createProxy

  1. /**
  2. * Create an AOP proxy for the given bean.
  3. * 为指定 bean 创建代理对象
  4. */
  5. protected Object createProxy(Class<?> beanClass, @Nullable String beanName, @Nullable Object[] specificInterceptors, TargetSource targetSource) {
  6. if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
  7. AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory)
  8. this.beanFactory, beanName, beanClass);
  9. }
  10. // 创建代理的⼯作交给ProxyFactory
  11. ProxyFactory proxyFactory = new ProxyFactory();
  12. proxyFactory.copyFrom(this);
  13. // 根据⼀些情况判断是否要设置proxyTargetClass=true
  14. if (!proxyFactory.isProxyTargetClass()) {
  15. if (shouldProxyTargetClass(beanClass, beanName)) {
  16. proxyFactory.setProxyTargetClass(true);
  17. }
  18. else {
  19. evaluateProxyInterfaces(beanClass, proxyFactory);
  20. }
  21. }
  22. // 把指定和通⽤拦截对象合并, 并都适配成Advisor
  23. Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
  24. proxyFactory.addAdvisors(advisors);
  25. // 设置参数
  26. proxyFactory.setTargetSource(targetSource);
  27. customizeProxyFactory(proxyFactory);
  28. proxyFactory.setFrozen(this.freezeProxy);
  29. if (advisorsPreFiltered()) {
  30. proxyFactory.setPreFiltered(true);
  31. }
  32. // 上⾯准备做完就开始创建代理
  33. return proxyFactory.getProxy(getProxyClassLoader());
  34. }

接着跟进到ProxyFactory中

public class ProxyFactory extends ProxyCreatorSupport {
    public Object getProxy(ClassLoader classLoader) {
        // ⽤ProxyFactory创建AopProxy, 然后⽤AopProxy创建Proxy, 所以这⾥重要的是看获取的AopProxy
        // 对象是什么,
        // 然后进去看怎么创建动态代理, 提供了两种:jdk proxy, cglib
        return createAopProxy().getProxy(classLoader);
        }
    }

    public class ProxyCreatorSupport extends AdvisedSupport {
        private AopProxyFactory aopProxyFactory;
        public ProxyCreatorSupport() {
            this.aopProxyFactory = new DefaultAopProxyFactory();
        }
        protected final synchronized AopProxy createAopProxy() {
            if (!this.active) {
                activate();
            }
            //先获取创建AopProxy的⼯⼚, 再由此创建AopProxy
            return getAopProxyFactory().createAopProxy(this);
        }

    public AopProxyFactory getAopProxyFactory() {
        return this.aopProxyFactory;
    }
}

流程就是⽤AopProxyFactory创建AopProxy, 再⽤AopProxy创建代理对象,这⾥的AopProxyFactory默认是DefaultAopProxyFactory,看他的createAopProxy⽅法

public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
    @Override
    public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
        if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
            Class<?> targetClass = config.getTargetClass();
            if (targetClass == null) {
                throw new AopConfigException("TargetSource cannot determine target class: "
                + "Either an interface or a target is required for proxy creation.");
            }
            if (targetClass.isInterface()) {
                return new JdkDynamicAopProxy(config);
            }
            return new ObjenesisCglibAopProxy(config);
        } else {
            return new JdkDynamicAopProxy(config);
        }
   }

    /**
        * Determine whether the supplied {@link AdvisedSupport} has only the
        * {@link org.springframework.aop.SpringProxy} interface specified (or no
        * proxy interfaces specified at all).
    */
    private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
        Class<?>[] interfaces = config.getProxiedInterfaces();
        return (interfaces.length == 0 || (interfaces.length == 1 && SpringProxy.class.equals(interfaces[0])));
    }
}

这⾥决定创建代理对象是⽤JDK Proxy,还是⽤ Cglib 了,最简单的从使⽤⽅⾯使⽤来说:设置proxyTargetClass=true强制使⽤Cglib 代理,什么参数都不设并且对象类实现了接⼝则默认⽤JDK 代理,如果没有实现接⼝则也必须⽤Cglib
ProxyFactory#getProxy(java.lang.ClassLoader)——— CglibAopProxy#getProxy(java.lang.ClassLoader)

@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
    if (logger.isTraceEnabled()) {
        logger.trace("Creating CGLIB proxy: " + this.advised.getTargetSource());
    }
    try {
        Class<?> rootClass = this.advised.getTargetClass();
        Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");
        Class<?> proxySuperClass = rootClass;
        if (ClassUtils.isCglibProxyClass(rootClass)) {
            proxySuperClass = rootClass.getSuperclass();
            Class<?>[] additionalInterfaces = rootClass.getInterfaces();
            for (Class<?> additionalInterface : additionalInterfaces) {
                this.advised.addInterface(additionalInterface);
            }
        }
        // Validate the class, writing log messages as necessary.
        validateClassIfNecessary(proxySuperClass, classLoader);
        // 配置 Cglib 增强
        Enhancer enhancer = createEnhancer();
        if (classLoader != null) {
            enhancer.setClassLoader(classLoader);
            if (classLoader instanceof SmartClassLoader && ((SmartClassLoader)classLoader).isClassReloadable(proxySuperClass)) {
                enhancer.setUseCache(false);
            }
        }
        enhancer.setSuperclass(proxySuperClass);
        enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
        enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
        enhancer.setStrategy(new ClassLoaderAwareUndeclaredThrowableStrategy(classLoader));
        Callback[] callbacks = getCallbacks(rootClass);
        Class<?>[] types = new Class<?>[callbacks.length];
        for (int x = 0; x < types.length; x++) {
            types[x] = callbacks[x].getClass();
        }
        // fixedInterceptorMap only populated at this point, after getCallbacks call above
        enhancer.setCallbackFilter(new ProxyCallbackFilter(this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
        enhancer.setCallbackTypes(types);
        // ⽣成代理类,并且创建⼀个代理类的实例
        return createProxyClassAndInstance(enhancer, callbacks);
    }
    catch (CodeGenerationException | IllegalArgumentException ex) {
        throw new AopConfigException("Could not generate CGLIB subclass of " +
        this.advised.getTargetClass() +
        ": Common causes of this problem include using a final class or anon-visible class",ex);
    }
    catch (Throwable ex) {
        // TargetSource.getTarget() failed
        throw new AopConfigException("Unexpected AOP exception", ex);
    }
}

AOP源码分析类⽅法调⽤关系课堂讲解过程中记录

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean
调⽤
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization
调⽤
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessAfterInitialization(后置处理器AbstractAutoProxyCreator完成bean代理对象创建)
调⽤
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary
调⽤
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#createProxy (在这⼀步把委托对象的aop增强和通⽤拦截进⾏合并,最终给代理对象)
调⽤
org.springframework.aop.framework.DefaultAopProxyFactory#createAopProxy
调⽤
org.springframework.aop.framework.CglibAopProxy#getProxy(java.lang.ClassLoader)

2. Spring声明式事务控制

声明式事务很⽅便,尤其纯注解模式,仅仅⼏个注解就能控制事务了
思考:这些注解都做了什么?好神奇!
@EnableTransactionManagement @Transactional

2.1 @EnableTransactionManagement

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(TransactionManagementConfigurationSelector.class)
public @interface EnableTransactionManagement {

@EnableTransactionManagement 注解使⽤ @Import 标签引⼊了TransactionManagementConfigurationSelector类,这个类⼜向容器中导⼊了两个重要的组件
image.png

2.2 加载事务控制组件

2.2.1 AutoProxyRegistrar

AutoProxyRegistrar 类的 registerBeanDefinitions ⽅法中⼜注册了⼀个组件
image.png
进⼊ AopConfigUtils.registerAutoProxyCreatorIfNecessary ⽅法
image.png
发现最终,注册了⼀个叫做 InfrastructureAdvisorAutoProxyCreator 的 Bean,⽽这个类是AbstractAutoProxyCreator 的⼦类,实现了 SmartInstantiationAwareBeanPostProcessor 接⼝

public class InfrastructureAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator
public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator
public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware

继承体系结构图如下
image.png
它实现了SmartInstantiationAwareBeanPostProcessor,说明这是⼀个后置处理器,⽽且跟spring AOP 开启@EnableAspectJAutoProxy 时注册的 AnnotationAwareAspectJProxyCreator实现的是同⼀个接⼝,所以说,声明式事务是 springAOP 思想的⼀种应⽤

2.2.2 ProxyTransactionManagementConfiguration 组件

/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.transaction.annotation;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
import org.springframework.transaction.config.TransactionManagementConfigUtils;
import org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor;
import org.springframework.transaction.interceptor.TransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionInterceptor;
/**
* {@code @Configuration} class that registers the Spring infrastructure
beans
* necessary to enable proxy-based annotation-driven transaction
management.
*
* @author Chris Beams
* @since 3.1
* @see EnableTransactionManagement
* @see TransactionManagementConfigurationSelector
*/
@Configuration
public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {
    @Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor() {
        // 事务增强器
        BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
        // 向事务增强器中注⼊ 属性解析器 transactionAttributeSource
        advisor.setTransactionAttributeSource(transactionAttributeSource());
        // 向事务增强器中注⼊ 事务拦截器 transactionInterceptor
        advisor.setAdvice(transactionInterceptor());
        if (this.enableTx != null) {
            advisor.setOrder(this.enableTx.<Integer>getNumber("order"));
        }
        return advisor;
    }

    @Bean
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    // 属性解析器 transactionAttributeSource
    public TransactionAttributeSource transactionAttributeSource() {
        return new AnnotationTransactionAttributeSource();
    }

    @Bean
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    // 事务拦截器 transactionInterceptor
    public TransactionInterceptor transactionInterceptor() {
        TransactionInterceptor interceptor = new TransactionInterceptor();
        interceptor.setTransactionAttributeSource(transactionAttributeSource());
        if (this.txManager != null) {
            interceptor.setTransactionManager(this.txManager);
        }
        return interceptor;
    }
}

ProxyTransactionManagementConfiguration是⼀个容器配置类,注册了⼀个组件transactionAdvisor,称为事务增强器,然后在这个事务增强器中⼜注⼊了两个属性:transactionAttributeSource,即属性解析器transactionAttributeSource 和 事务拦截器 transactionInterceptor

1. 属性解析器 AnnotationTransactionAttributeSource 部分源码如下

image.png
属性解析器有⼀个成员变量是annotationParsers,是⼀个集合,可以添加多种注解解析器(TransactionAnnotationParser),我们关注 Spring 的注解解析器,部分源码如下
image.png
属性解析器的作⽤之⼀就是⽤来解析@Transaction注解

2. TransactionInterceptor 事务拦截器,部分源码如下

image.png
image.png

2.2.3 上述组件如何关联起来的?

  • 事务拦截器实现了MethodInterceptor接⼝,追溯⼀下上⾯提到的InfrastructureAdvisorAutoProxyCreator后置处理器,它会在代理对象执⾏⽬标⽅法的时候获取其拦截器链,⽽拦截器链就是这个TransactionInterceptor,这就把这两个组件联系起来;
  • 构造⽅法传⼊PlatformTransactionManager(事务管理器)、TransactionAttributeSource(属性解析器),但是追溯⼀下上⾯贴的ProxyTransactionManagementConfiguration的源码,在注册事务拦截器的时候并没有调⽤这个带参构造⽅法,⽽是调⽤的⽆参构造⽅法,然后再调⽤set⽅法注⼊这两个属性,效果⼀样。

    2.2.4 invokeWithinTransaction ⽅法,部分源码如下(关注1、2、3、4 标注处)

    image.png
    image.png

    1. 声明式事务分析课堂讲解过程中记录

    ``` @EnableTransactionManagement 注解 1)通过@import引⼊了TransactionManagementConfigurationSelector类 它的selectImports⽅法导⼊了另外两个类:AutoProxyRegistrar和ProxyTransactionManagementConfiguration

2)AutoProxyRegistrar类分析 ⽅法registerBeanDefinitions中,引⼊了其他类,通过AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry)引⼊InfrastructureAdvisorAutoProxyCreator,它继承了AbstractAutoProxyCreator,是⼀个后置处理器类

3)ProxyTransactionManagementConfiguration 是⼀个添加了@Configuration注解的配置类 (注册bean) 注册事务增强器(注⼊属性解析器、事务拦截器) 属性解析器:AnnotationTransactionAttributeSource,内部持有了⼀个解析器集合Set annotationParsers; 具体使⽤的是SpringTransactionAnnotationParser解析器,⽤来解析@Transactional的事务属性 事务拦截器:TransactionInterceptor实现了MethodInterceptor接⼝,该通⽤拦截 会在产⽣代理对象之前和aop增强合并,最终⼀起影响到代理对象TransactionInterceptor的invoke⽅法中invokeWithinTransaction会触发原有业务逻辑调⽤(增强事务) ```