7.1 时机点分析

  1. public void test() {
  2. ApplicationContext context = AnnotationConfigApplicationContext(SpringConfig.class);
  3. TestBean bean = context.getBean(TestBean.class);
  4. bean.tech();
  5. }

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

7.2 代理对象创建流程

  1. AbstractAutowireCapableBeanFactory#initializeBean ```java /**
  • 初始化Bean
  • 包括Bean后置处理器初始化
  • Bean的⼀些初始化⽅法的执⾏init-method
  • Bean的实现的声明周期相关接⼝的属性注⼊ */ protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) { // 执⾏所有的AwareMethods if (System.getSecurityManager() != null) {

    1. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
    2. invokeAwareMethods(beanName, bean);
    3. return null;
    4. }, getAccessControlContext());

    }else {

    1. invokeAwareMethods(beanName, bean);

    } Object wrappedBean = bean;

    if (mbd == null || !mbd.isSynthetic()) {

    1. // 执⾏所有的BeanPostProcessor#postProcessBeforeInitialization 初始化之前
    2. // 的处理器⽅法
    3. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean,
    4. beanName);

    } try {

    1. // 这⾥就开始执⾏afterPropertiesSet(实现了InitializingBean接⼝)⽅法和
    2. initMethod
    3. invokeInitMethods(beanName, wrappedBean, mbd);

    } catch (Throwable ex) { throw new BeanCreationException(

    1. (mbd != null ? mbd.getResourceDescription() : null),
    2. beanName, "Invocation of init method failed", ex);

    }

    if (mbd == null || !mbd.isSynthetic()) {

    1. // 整个Bean初始化完成,执⾏后置处理器⽅法
    2. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean,
    3. beanName);

    } return wrappedBean; } ```

  1. AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization

    1. @Override
    2. public Object applyBeanPostProcessorsAfterInitialization(Object
    3. existingBean, String beanName) throws BeansException {
    4. Object result = existingBean;
    5. // 循环执⾏后置处理器
    6. for (BeanPostProcessor processor : getBeanPostProcessors()) {
    7. Object current = processor.postProcessAfterInitialization(result,
    8. beanName);
    9. if (current == null) {
    10. return result;
    11. }
    12. result = current;
    13. }
    14. return result;
    15. }
  2. 上一步找到名为proxyTargetClass的这个BeanPostprocessor,然后看他执行的postProcessAfterInitialization方法。

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

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

    1. protected Object wrapIfNecessary(Object bean, String beanName, Object
    2. cacheKey) {
    3. // targetSourcedBeans包含,说明前⾯创建过
    4. if (StringUtils.hasLength(beanName) &&
    5. this.targetSourcedBeans.contains(beanName)) {
    6. return bean;
    7. }
    8. if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
    9. return bean;
    10. }
    11. if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(),
    12. beanName)) {
    13. this.advisedBeans.put(cacheKey, Boolean.FALSE);
    14. return bean;
    15. }
    16. // Create proxy if we have advice.
    17. // 得到所有候选Advisor,对Advisors和bean的⽅法双层遍历匹配,最终得到⼀个
    18. // List<Advisor>,即specificInterceptors
    19. Object[] specificInterceptors =
    20. getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
    21. if (specificInterceptors != DO_NOT_PROXY) {
    22. this.advisedBeans.put(cacheKey, Boolean.TRUE);
    23. // 重点,创建代理对象
    24. Object proxy = createProxy(
    25. bean.getClass(), beanName, specificInterceptors, new
    26. SingletonTargetSource(bean));
    27. this.proxyTypes.put(cacheKey, proxy.getClass());
    28. return proxy;
    29. }
    30. this.advisedBeans.put(cacheKey, Boolean.FALSE);
    31. return bean;
    32. }
  5. AbstractAutoProxyCreator#createProxy ```java /**

  • Create an AOP proxy for the given bean.
  • 为指定 bean 创建代理对象 */ protected Object createProxy(Class<?> beanClass, @Nullable String beanName, @Nullable Object[] specificInterceptors, TargetSource targetSource) { if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
    1. AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory)
    2. this.beanFactory, beanName, beanClass);
    } // 创建代理的⼯作交给ProxyFactory ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.copyFrom(this); // 根据⼀些情况判断是否要设置proxyTargetClass=true if (!proxyFactory.isProxyTargetClass()) {
    1. if (shouldProxyTargetClass(beanClass, beanName)) {
    2. proxyFactory.setProxyTargetClass(true);
    3. }else {
    4. evaluateProxyInterfaces(beanClass, proxyFactory);
    5. }
    } // 把指定和通⽤拦截对象合并, 并都适配成Advisor Advisor[] advisors = buildAdvisors(beanName, specificInterceptors); proxyFactory.addAdvisors(advisors); // 设置参数 proxyFactory.setTargetSource(targetSource); customizeProxyFactory(proxyFactory); proxyFactory.setFrozen(this.freezeProxy); if (advisorsPreFiltered()) {
    1. proxyFactory.setPreFiltered(true);
    } // 上⾯准备做完就开始创建代理 return proxyFactory.getProxy(getProxyClassLoader()); } ```
  1. getProxy

    1. public class ProxyFactory extends ProxyCreatorSupport {
    2. public Object getProxy(ClassLoader classLoader) {
    3. // ⽤ProxyFactory创建AopProxy, 然后⽤AopProxy创建Proxy, 所以这⾥重要的是看获取的
    4. // AopProxy
    5. // 对象是什么,
    6. // 然后进去看怎么创建动态代理, 提供了两种:jdk proxy, cglib
    7. return createAopProxy().getProxy(classLoader);
    8. }
    9. }
    10. public class ProxyCreatorSupport extends AdvisedSupport {
    11. private AopProxyFactory aopProxyFactory;
    12. public ProxyCreatorSupport() {
    13. this.aopProxyFactory = new DefaultAopProxyFactory();
    14. }
    15. protected final synchronized AopProxy createAopProxy() {
    16. if (!this.active) {
    17. activate();
    18. }
    19. //先获取创建AopProxy的⼯⼚, 再由此创建AopProxy
    20. return getAopProxyFactory().createAopProxy(this);
    21. }
    22. public AopProxyFactory getAopProxyFactory() {
    23. return this.aopProxyFactory;
    24. }
    25. }
  2. 流程就是⽤AopProxyFactory创建AopProxy, 再⽤AopProxy创建代理对象,这⾥的AopProxyFactory默认是DefaultAopProxyFactory,看他的createAopProxy⽅法

    1. public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
    2. @Override
    3. public AopProxy createAopProxy(AdvisedSupport config) throws
    4. AopConfigException {
    5. if (config.isOptimize() || config.isProxyTargetClass() ||
    6. hasNoUserSuppliedProxyInterfaces(config)) {
    7. Class<?> targetClass = config.getTargetClass();
    8. if (targetClass == null) {
    9. throw new AopConfigException("TargetSource cannot determine target
    10. class: "
    11. + "Either an interface or a target is required for proxy
    12. creation.");
    13. if (targetClass.isInterface()) {
    14. return new JdkDynamicAopProxy(config);
    15. }
    16. return new ObjenesisCglibAopProxy(config);
    17. } else {
    18. return new JdkDynamicAopProxy(config);
    19. }
    20. }
    21. /**
    22. * Determine whether the supplied {@link AdvisedSupport} has only the
    23. * {@link org.springframework.aop.SpringProxy} interface specified (or no
    24. * proxy interfaces specified at all).
    25. */
    26. private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
    27. Class<?>[] interfaces = config.getProxiedInterfaces();
    28. return (interfaces.length == 0 || (interfaces.length == 1 &&
    29. SpringProxy.class.equals(interfaces[0])));
    30. }
    31. }
    32. }
  3. 这⾥决定创建代理对象是⽤JDK Proxy,还是⽤ Cglib 了,最简单的从使⽤⽅⾯使⽤来说:设置proxyTargetClass=true强制使⽤Cglib 代理,什么参数都不设并且对象类实现了接⼝则默认⽤JDK 代理,如果没有实现接⼝则也必须⽤Cglib

    1. @Override
    2. public Object getProxy(@Nullable ClassLoader classLoader) {
    3. if (logger.isTraceEnabled()) {
    4. logger.trace("Creating CGLIB proxy: " + this.advised.getTargetSource());
    5. }
    6. try {
    7. Class<?> rootClass = this.advised.getTargetClass();
    8. Assert.state(rootClass != null, "Target class must be available for
    9. creating a CGLIB proxy");
    10. Class<?> proxySuperClass = rootClass;
    11. if (ClassUtils.isCglibProxyClass(rootClass)) {
    12. proxySuperClass = rootClass.getSuperclass();
    13. Class<?>[] additionalInterfaces = rootClass.getInterfaces();
    14. for (Class<?> additionalInterface : additionalInterfaces) {
    15. this.advised.addInterface(additionalInterface);
    16. }
    17. }
    18. // Validate the class, writing log messages as necessary.
    19. validateClassIfNecessary(proxySuperClass, classLoader);
    20. // 配置 Cglib 增强
    21. Enhancer enhancer = createEnhancer();
    22. if (classLoader != null) {
    23. enhancer.setClassLoader(classLoader);
    24. if (classLoader instanceof SmartClassLoader &&
    25. ((SmartClassLoader)
    26. classLoader).isClassReloadable(proxySuperClass)) {
    27. enhancer.setUseCache(false);
    28. }
    29. }
    30. enhancer.setSuperclass(proxySuperClass);
    31. enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
    32. enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
    33. enhancer.setStrategy(new
    34. ClassLoaderAwareUndeclaredThrowableStrategy(classLoader));
    35. Callback[] callbacks = getCallbacks(rootClass);
    36. Class<?>[] types = new Class<?>[callbacks.length];
    37. for (int x = 0; x < types.length; x++) {
    38. types[x] = callbacks[x].getClass();
    39. }
    40. // fixedInterceptorMap only populated at this point, after getCallbacks
    41. // call above
    42. enhancer.setCallbackFilter(new ProxyCallbackFilter(
    43. this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap,
    44. this.fixedInterceptorOffset));
    45. enhancer.setCallbackTypes(types);
    46. // ⽣成代理类,并且创建⼀个代理类的实例
    47. return createProxyClassAndInstance(enhancer, callbacks);
    48. } catch (CodeGenerationException | IllegalArgumentException ex) {
    49. throw new AopConfigException("Could not generate CGLIB subclass of " +
    50. this.advised.getTargetClass() +
    51. ": Common causes of this problem include using a final class or a
    52. non-visible class",ex);
    53. } catch (Throwable ex) {
    54. // TargetSource.getTarget() failed
    55. throw new AopConfigException("Unexpected AOP exception", ex);
    56. }
    57. }
  4. 总结:AOP代理对象就是在容器初始化时,创建了Bean,Bean创建时的一个BeanPostProcessor的时机进行AOP代理对象的创建。

    7.3 Spring声明式事务控制

    主要看几个注解:@EnableTransactionManagement @Transactional

    7.3.1 @EnableTransactionManagement

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

    1. @Target(ElementType.TYPE)
    2. @Retention(RetentionPolicy.RUNTIME)
    3. @Documented
    4. @Import(TransactionManagementConfigurationSelector.class)
    5. public @interface EnableTransactionManagement {
  6. 这个类⼜向容器中导⼊了两个重要的组件:AutoProxyRegistrar和ProxyTransactionManagementConfiguration ```java public class TransactionManagementConfigurationSelector extends AdviceModeImportSelector { @Override protected String[] selectImports(AdviceMode adviceMode) {

    1. switch (adviceMode) {
    2. case PROXY:
    3. return new String[] {AutoProxyRegistrar.class.getName(),
    4. ProxyTransactionManagementConfiguration.class.getName()};
    5. case ASPECTJ:
    6. return new String[] {determineTransactionAspectClass()};
    7. default:
    8. return null;
    9. }

    }

}

  1. <a name="o5bb9"></a>
  2. ## 7.3.2 加载事务控制组件
  3. 1. **AutoProxyRegistrar **类的 registerBeanDefinitions ⽅法中⼜注册了⼀个组件AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
  4. ```java
  5. @Override
  6. public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
  7. boolean candidateFound = false;
  8. Set<String> annTypes = importingClassMetadata.getAnnotationTypes();
  9. for (String annType : annTypes) {
  10. AnnotationAttributes candidate = AnnotationConfigUtils.attributesFor(importingClassMetadata, annType);
  11. if (candidate == null) {
  12. continue;
  13. }
  14. Object mode = candidate.get("mode");
  15. Object proxyTargetClass = candidate.get("proxyTargetClass");
  16. if (mode != null && proxyTargetClass != null && AdviceMode.class == mode.getClass() && Boolean.class == proxyTargetClass.getClass()) {
  17. candidateFound = true;
  18. if (mode == AdviceMode.PROXY) {
  19. AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
  20. if ((Boolean) proxyTargetClass) {
  21. AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
  22. return;
  23. }
  24. }
  25. }
  26. }
  27. }
  1. 进⼊ AopConfigUtils.registerAutoProxyCreatorIfNecessary ⽅法,发现最终,注册了⼀个叫做 InfrastructureAdvisorAutoProxyCreator 的 Bean,⽽这个类是AbstractAutoProxyCreator 的⼦类,实现了 SmartInstantiationAwareBeanPostProcessor 接⼝

    1. @Nullable
    2. public static BeanDefinition registerAutoProxyCreatorIfNecessary(
    3. BeanDefinitionRegistry registry, @Nullable Object source) {
    4. return registerOrEscalateApcAsRequired(InfrastructureAdvisorAutoProxyCreator.class, registry, source);
    5. }
  2. 它实现了SmartInstantiationAwareBeanPostProcessor,说明这是⼀个后置处理器,⽽且跟spring AOP 开启@EnableAspectJAutoProxy 时注册的 AnnotationAwareAspectJProxyCreator实现的是同⼀个接⼝,所以说,声明式事务是 springAOP 思想的⼀种应⽤

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

    1. @Configuration
    2. public class ProxyTransactionManagementConfiguration extends
    3. AbstractTransactionManagementConfiguration {
    4. @Bean(name =
    5. TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
    6. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    7. public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor()
    8. {
    9. // 事务增强器
    10. BeanFactoryTransactionAttributeSourceAdvisor advisor = new
    11. BeanFactoryTransactionAttributeSourceAdvisor();
    12. // 向事务增强器中注⼊ 属性解析器 transactionAttributeSource
    13. advisor.setTransactionAttributeSource(transactionAttributeSource());
    14. // 向事务增强器中注⼊ 事务拦截器 transactionInterceptor
    15. advisor.setAdvice(transactionInterceptor());
    16. if (this.enableTx != null) {
    17. advisor.setOrder(this.enableTx.<Integer>getNumber("order"));
    18. }
    19. return advisor;
    20. }
    21. @Bean
    22. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    23. // 属性解析器 transactionAttributeSource
    24. public TransactionAttributeSource transactionAttributeSource() {
    25. return new AnnotationTransactionAttributeSource();
    26. }
    27. @Bean
    28. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    29. // 事务拦截器 transactionInterceptor
    30. public TransactionInterceptor transactionInterceptor() {
    31. TransactionInterceptor interceptor = new TransactionInterceptor();
    32. interceptor.setTransactionAttributeSource(transactionAttributeSource());
    33. if (this.txManager != null) {
    34. interceptor.setTransactionManager(this.txManager);
    35. }
    36. return interceptor;
    37. }
    38. }
  4. 属性解析器的作⽤之⼀就是⽤来解析@Transaction注解,各种属性会有对应的解析

  5. 上述组件如何关联起来的?
  • 事务拦截器实现了MethodInterceptor接⼝,追溯⼀下上⾯提到的InfrastructureAdvisorAutoProxyCreator后置处理器,它会在代理对象执⾏⽬标⽅法的时候获取其拦截器链,⽽拦截器链就是这个TransactionInterceptor,这就把这两个组件联系起来;
  • 构造⽅法传⼊PlatformTransactionManager(事务管理器)、TransactionAttributeSource(属性解析器),但是追溯⼀下上⾯贴的ProxyTransactionManagementConfiguration的源码,在注册事务拦截器的时候并没有调⽤这个带参构造⽅法,⽽是调⽤的⽆参构造⽅法,然后再调⽤set⽅法注⼊这两个属性,效果⼀样。
  1. 解析过程: ```java @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会触发原有业务逻辑调⽤(增强事务) ```