一、AOP动态代理对象创建初探

1 前置知识

https://www.yuque.com/wuxiangwuwo/dfvedv/vd90qo#ttKT4
AbstractAutowireCapableBeanFactory类的doCreateBean方法是创建bean的开始,doCreateBean调用的AbstractAutowireCapableBeanFactory#initializeBean方法负责初始化bean,initializeBean方法调用的AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization方法负责执行BeanPostProcessor的接口实现类中的postProcessAfterInitialization方法。
01-AOP动态代理对象的创建 - 图1
01-AOP动态代理对象的创建 - 图2

2 AbstractAutoProxyCreator#postProcessAfterInitialization

创建代理对象的后置处理器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. // 检查下该类是否已经暴露过了
  10. // (可能已经创建了,⽐如A依赖B时,创建A时候,就会先去创建B,
  11. // 当真正需要创建B时,就没必要再代理⼀次已经代理过的对象),避免重复创建
  12. Object cacheKey = getCacheKey(bean.getClass(), beanName);
  13. if (this.earlyProxyReferences.remove(cacheKey) != bean) {
  14. return wrapIfNecessary(bean, beanName, cacheKey);
  15. }
  16. }
  17. return bean;
  18. }

3 AbstractAutoProxyCreator#wrapIfNecessary

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

4 AbstractAutoProxyCreator#createProxy

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

5 ProxyFactory

接着跟进到ProxyFactory中

  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. }

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

6 DefaultAopProxyFactory#createAopProxy

  1. public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
  2. @Override
  3. public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
  4. if (config.isOptimize() || config.isProxyTargetClass()
  5. || hasNoUserSuppliedProxyInterfaces(config)) {
  6. Class<?> targetClass = config.getTargetClass();
  7. if (targetClass == null) {
  8. throw new AopConfigException("TargetSource cannot determine target class: "
  9. + "Either an interface or a target is required for proxy creation.");
  10. }
  11. if (targetClass.isInterface()) {
  12. return new JdkDynamicAopProxy(config);
  13. }
  14. return new ObjenesisCglibAopProxy(config);
  15. } else {
  16. return new JdkDynamicAopProxy(config);
  17. }
  18. }
  19. /**
  20. ● Determine whether the supplied {@link AdvisedSupport} has only the
  21. ● {@link org.springframework.aop.SpringProxy} interface specified (or no
  22. * proxy interfaces specified at all).
  23. */
  24. private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
  25. Class<?>[] interfaces = config.getProxiedInterfaces();
  26. return (interfaces.length == 0 ||
  27. (interfaces.length == 1 && SpringProxy.class.equals(interfaces[0])));
  28. }
  29. }

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

7 CglibAopProxy#getProxy

  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 creating a CGLIB proxy");
  9. Class<?> proxySuperClass = rootClass;
  10. if (ClassUtils.isCglibProxyClass(rootClass)) {
  11. proxySuperClass = rootClass.getSuperclass();
  12. Class<?>[] additionalInterfaces = rootClass.getInterfaces();
  13. for (Class<?> additionalInterface : additionalInterfaces) {
  14. this.advised.addInterface(additionalInterface);
  15. }
  16. }
  17. // Validate the class, writing log messages as necessary.
  18. validateClassIfNecessary(proxySuperClass, classLoader);
  19. // 配置 Cglib 增强
  20. Enhancer enhancer = createEnhancer();
  21. if (classLoader != null) {
  22. enhancer.setClassLoader(classLoader);
  23. if (classLoader instanceof SmartClassLoader && ((SmartClassLoader)
  24. classLoader).isClassReloadable(proxySuperClass)) {
  25. enhancer.setUseCache(false);
  26. }
  27. }
  28. enhancer.setSuperclass(proxySuperClass);
  29. enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
  30. enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
  31. enhancer.setStrategy(new ClassLoaderAwareUndeclaredThrowableStrategy(classLoader));
  32. Callback[] callbacks = getCallbacks(rootClass);
  33. Class<?>[] types = new Class<?>[callbacks.length];
  34. for (int x = 0; x < types.length; x++) {
  35. types[x] = callbacks[x].getClass();
  36. }
  37. // fixedInterceptorMap only populated at this point, after getCallbacks call above
  38. enhancer.setCallbackFilter(new ProxyCallbackFilter(
  39. this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap,
  40. this.fixedInterceptorOffset));
  41. enhancer.setCallbackTypes(types);
  42. // ⽣成代理类,并且创建⼀个代理类的实例
  43. return createProxyClassAndInstance(enhancer, callbacks);
  44. } catch (CodeGenerationException | IllegalArgumentException ex) {
  45. throw new AopConfigException("Could not generate CGLIB subclass of "
  46. + this.advised.getTargetClass() +
  47. ": Common causes of this problem include using a final class or a non-visible class",
  48. ex);
  49. } catch (Throwable ex) {
  50. // TargetSource.getTarget() failed
  51. throw new AopConfigException("Unexpected AOP exception", ex);
  52. }
  53. }

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

  1. org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#i
  2. nitializeBean
  3. 调⽤
  4. org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#a
  5. pplyBeanPostProcessorsAfterInitialization
  6. 调⽤
  7. org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProce
  8. ssAfterInitialization(后置处理器AbstractAutoProxyCreator完成bean代理对象创建)
  9. 调⽤
  10. org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNec
  11. essary
  12. 调⽤
  13. org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#createPro
  14. xy (在这⼀步把委托对象的aop增强和通⽤拦截进⾏合并,最终给代理对象)
  15. 调⽤
  16. org.springframework.aop.framework.DefaultAopProxyFactory#createAopProxy
  17. 调⽤
  18. org.springframework.aop.framework.CglibAopProxy#getProxy(java.lang.ClassLoader)

时序图
image.png