show: stepversion: 1.0
enable_checker: true

第十章、浅谈SpringFramework AOP代理对象创建

前言介绍

上一章节的学习中,我们对Springframework的AOP基本概念和用法有了基本的了解熟悉,接着本文继续学习Springframework核心技术点AOP技术的源码

实验环境准备

实验环境:

  • SpringFramework版本
  • Springframework5.0.x
  • 开发环境
  • JAR管理:gradle 4.9/ Maven3.+
  • 开发IDE:IntelliJ IDEA 2018.2.5
  • JDK:jdk1.8.0_31
  • Git Server:Git fro window 2.8.3
  • Git Client:SmartGit18.1.5(可选)

Spring AOP代理

在上一章的学习,我们知道了Spring AOP是AOP的实现方案之一,这种方案有别于AspectJ,这是一种将Spring IOC技术和Aop进行结合的技术,在Spring2.0+引用了AspectJ的jar,并进行自己的实现,这是一种基于代理的技术,具体来说是基于JDK动态代理和CBLIB动态代理的技术
为什么说Spring AOP实现基于IOC?首先挑出一个比较重要的Spring AOP自动创建代理类:DefaultAdvisorAutoProxyCreator
在IDEA中生成一张DefaultAdvisorAutoProxyCreator的类图
在这里插入图片描述
从图可以看出DefaultAdvisorAutoProxyCreator实现了后置处理器的接口,也就是说DefaultAdvisorAutoProxyCreator是一个后置处理器

使用调试代码

所以,本文要写个DefaultAdvisorAutoProxyCreator例子进行学习,学习源码,建议通过debug进行学习
User.java:

  1. package com.example.aop.bean;
  2. public class User {
  3. private String username;
  4. private String password;
  5. public String getUsername() {
  6. return username;
  7. }
  8. public void setUsername(String username) {
  9. this.username = username;
  10. }
  11. public String getPassword() {
  12. return password;
  13. }
  14. public void setPassword(String password) {
  15. this.password = password;
  16. }
  17. @Override
  18. public String toString() {
  19. return "User{" +
  20. "username='" + username + '\'' +
  21. ", password='" + password + '\'' +
  22. '}';
  23. }
  24. }

UserService.java:

  1. package com.example.aop.service;
  2. import com.example.aop.bean.User;
  3. /**
  4. *
  5. <pre>
  6. * UserService
  7. * </pre>
  8. *
  9. *
  10. <pre>
  11. * @author mazq
  12. * 修改记录
  13. * 修改后版本: 修改人: 修改日期: 2020/11/20 18:02 修改内容:
  14. * </pre>
  15. */
  16. public interface UserService {
  17. User addUser(User user);
  18. User getUser();
  19. String findUserNameById(Long id);
  20. }

UserServiceImpl.java:

  1. package com.example.aop.service.impl;
  2. import com.example.aop.bean.User;
  3. import com.example.aop.service.UserService;
  4. import org.springframework.beans.BeanUtils;
  5. import org.springframework.stereotype.Service;
  6. /**
  7. *
  8. <pre>
  9. * UserServiceImpl
  10. * </pre>
  11. *
  12. *
  13. <pre>
  14. * @author mazq
  15. * 修改记录
  16. * 修改后版本: 修改人: 修改日期: 2020/11/20 17:57 修改内容:
  17. * </pre>
  18. */
  19. @Service
  20. public class UserServiceImpl implements UserService {
  21. private static User user = null;
  22. @Override
  23. public User addUser(User userDto) {
  24. user = new User();
  25. BeanUtils.copyProperties(userDto,user);
  26. return user;
  27. }
  28. @Override
  29. public User getUser() {
  30. return user;
  31. }
  32. @Override
  33. public String findUserNameById(Long id) {
  34. return "tom";
  35. }
  36. }

MethodInterceptor,是一个拦截方法的MethodInterceptor

  1. package com.example.aop.core.interceptor;
  2. import org.aopalliance.intercept.MethodInterceptor;
  3. import org.aopalliance.intercept.MethodInvocation;
  4. /**
  5. *
  6. <pre>
  7. * TestMethodInterceptor
  8. * </pre>
  9. *
  10. *
  11. <pre>
  12. * @author mazq
  13. * 修改记录
  14. * 修改后版本: 修改人: 修改日期: 2020/11/23 10:28 修改内容:
  15. * </pre>
  16. */
  17. public class TestMethodInterceptor implements MethodInterceptor {
  18. @Override
  19. public Object invoke(MethodInvocation methodInvocation) throws Throwable {
  20. System.out.println(String.format("方法调用前(before method invoke) :%s",methodInvocation));
  21. Object implObj = methodInvocation.proceed();
  22. System.out.println(String.format("方法调用后(after method invoke) :%s",implObj));
  23. return implObj;
  24. }
  25. }

配置类,拦截get开头的方法:

  1. package com.example.aop.config;
  2. import com.example.aop.core.interceptor.TestMethodInterceptor;
  3. import com.example.aop.service.UserService;
  4. import com.example.aop.service.impl.UserServiceImpl;
  5. import org.aopalliance.aop.Advice;
  6. import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
  7. import org.springframework.aop.support.NameMatchMethodPointcutAdvisor;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. /**
  11. *
  12. <pre>
  13. * SpringAutoProxyConfiguration
  14. * </pre>
  15. *
  16. *
  17. <pre>
  18. * @author mazq
  19. * 修改记录
  20. * 修改后版本: 修改人: 修改日期: 2020/11/26 14:57 修改内容:
  21. * </pre>
  22. */
  23. @Configuration
  24. public class SpringAutoProxyConfiguration {
  25. @Bean
  26. public UserService userService() {
  27. return new UserServiceImpl();
  28. }
  29. @Bean
  30. public Advice methodInterceptor() {
  31. return new TestMethodInterceptor();
  32. }
  33. @Bean
  34. public NameMatchMethodPointcutAdvisor nameMatchMethodPointcutAdvisor() {
  35. NameMatchMethodPointcutAdvisor nameMatchMethodPointcutAdvisor = new NameMatchMethodPointcutAdvisor();
  36. nameMatchMethodPointcutAdvisor.setMappedName("get*");
  37. nameMatchMethodPointcutAdvisor.setAdvice(methodInterceptor());
  38. return nameMatchMethodPointcutAdvisor;
  39. }
  40. @Bean
  41. public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
  42. return new DefaultAdvisorAutoProxyCreator();
  43. }
  44. }

测试类:TestApplication

  1. package com.example;
  2. import com.example.aop.config.SpringAspectJConfiguration;
  3. import com.example.aop.service.UserService;
  4. import com.example.config.AppConfiguration;
  5. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  6. /**
  7. *
  8. <pre>
  9. * TestController
  10. * </pre>
  11. *
  12. *
  13. <pre>
  14. * @author mazq
  15. * 修改记录
  16. * 修改后版本: 修改人: 修改日期: 2020/11/05 10:22 修改内容:
  17. * </pre>
  18. */
  19. public class TestApplication {
  20. public static void testSpringAopProxy() {
  21. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
  22. context.register(SpringAutoProxyConfiguration.class);
  23. context.refresh();
  24. //ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring_defaultAdvisorAutoProxyCreator_config.xml");
  25. UserService userService = context.getBean(UserService.class);
  26. User userDto = new User();
  27. userDto.setUsername("tom");
  28. userDto.setPassword("11");
  29. userService.addUser(userDto);
  30. System.out.println(String.format("用户数据打印:%s",userService.getUser().toString()));
  31. }
  32. public static void main(String[] args) {
  33. // 测试AOP代理对象
  34. testSpringAopProxy();
  35. }
  36. }

通过xml匹配文件也是可以实现的,spring_defaultAdvisorAutoProxyCreator_config.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  5. <!-- 具体业务实现类(target Object)-->
  6. <bean id="userService" class="com.example.aop.service.impl.UserServiceImpl"></bean>
  7. <!-- 定义MethodInterceptor -->
  8. <bean id="methodInterceptor" class="com.example.aop.core.interceptor.TestMethodInterceptor"></bean>
  9. <bean id="1" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
  10. <property name="mappedName" value="get*"></property>
  11. <property name="advice" ref="methodInterceptor"></property>
  12. </bean>
  13. <!-- 定义BeanNameAutoProxyCreator -->
  14. <bean id="autoProxyCreator" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator">
  15. </bean>
  16. </beans>

通过ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring_defaultAdvisorAutoProxyCreator_config.xml");获取ioc实例就行

Spring Bean创建

在前面博客,我们知道了,Spring ioc是怎么bean的,前面分析了,spring aop其实就是基于spring ioc实现的,是基于后置处理器,然后再加上动态代理实现的,所以我们可以通过debug方式,跟下源码:

  1. /**
  2. * Central method of this class: creates a bean instance,
  3. * populates the bean instance, applies post-processors, etc.
  4. * @see #doCreateBean
  5. */
  6. @Override
  7. protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  8. throws BeanCreationException {
  9. if (logger.isDebugEnabled()) {
  10. logger.debug("Creating instance of bean '" + beanName + "'");
  11. }
  12. RootBeanDefinition mbdToUse = mbd;
  13. // Make sure bean class is actually resolved at this point, and
  14. // clone the bean definition in case of a dynamically resolved Class
  15. // which cannot be stored in the shared merged bean definition.
  16. // ClassLoader加载BeanDefinition
  17. Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
  18. if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
  19. mbdToUse = new RootBeanDefinition(mbd);
  20. mbdToUse.setBeanClass(resolvedClass);
  21. }
  22. // Prepare method overrides.
  23. // 处理方法覆盖
  24. // 涉及bean 定义中的 <lookup-method /> 和 <replaced-method />,先放过 todo
  25. try {
  26. mbdToUse.prepareMethodOverrides();
  27. }
  28. catch (BeanDefinitionValidationException ex) {
  29. throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
  30. beanName, "Validation of method overrides failed", ex);
  31. }
  32. try {
  33. // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
  34. // 让InstantiationAwareBeanPostProcessor这个后置处理器有机会返回一个代理的实例,这个ioc源码学习先放过 todo
  35. Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
  36. if (bean != null) {
  37. return bean;
  38. }
  39. }
  40. catch (Throwable ex) {
  41. throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
  42. "BeanPostProcessor before instantiation of bean failed", ex);
  43. }
  44. try {
  45. // 重头戏,doCreateBean是实践执行bean创建的
  46. Object beanInstance = doCreateBean(beanName, mbdToUse, args);
  47. if (logger.isDebugEnabled()) {
  48. logger.debug("Finished creating instance of bean '" + beanName + "'");
  49. }
  50. return beanInstance;
  51. }
  52. catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
  53. // A previously detected exception with proper bean creation context already,
  54. // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
  55. throw ex;
  56. }
  57. catch (Throwable ex) {
  58. throw new BeanCreationException(
  59. mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
  60. }
  61. }

{@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])}

  1. /**
  2. * Actually create the specified bean. Pre-creation processing has already happened
  3. * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
  4. * <p>Differentiates between default bean instantiation, use of a
  5. * factory method, and autowiring a constructor.
  6. * @param beanName the name of the bean
  7. * @param mbd the merged bean definition for the bean
  8. * @param args explicit arguments to use for constructor or factory method invocation
  9. * @return a new instance of the bean
  10. * @throws BeanCreationException if the bean could not be created
  11. * @see #instantiateBean
  12. * @see #instantiateUsingFactoryMethod
  13. * @see #autowireConstructor
  14. */
  15. protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  16. throws BeanCreationException {
  17. // Instantiate the bean.
  18. BeanWrapper instanceWrapper = null;
  19. if (mbd.isSingleton()) {
  20. instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
  21. }
  22. // 不是FactoryBean的情况
  23. if (instanceWrapper == null) {
  24. // 1、创建Bean实例,但是还没设置属性
  25. instanceWrapper = createBeanInstance(beanName, mbd, args);
  26. }
  27. Object bean = instanceWrapper.getWrappedInstance();
  28. Class<?> beanType = instanceWrapper.getWrappedClass();
  29. if (beanType != NullBean.class) {
  30. mbd.resolvedTargetType = beanType;
  31. }
  32. // Allow post-processors to modify the merged bean definition.
  33. // 涉及到MergedBeanDefinitionPostProcessor,先跳过 todo
  34. synchronized (mbd.postProcessingLock) {
  35. if (!mbd.postProcessed) {
  36. try {
  37. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
  38. }
  39. catch (Throwable ex) {
  40. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  41. "Post-processing of merged bean definition failed", ex);
  42. }
  43. mbd.postProcessed = true;
  44. }
  45. }
  46. // Eagerly cache singletons to be able to resolve circular references
  47. // even when triggered by lifecycle interfaces like BeanFactoryAware.
  48. // 循环依赖的问题,单例bean才支持循环依赖
  49. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  50. isSingletonCurrentlyInCreation(beanName));
  51. if (earlySingletonExposure) {
  52. if (logger.isDebugEnabled()) {
  53. logger.debug("Eagerly caching bean '" + beanName +
  54. "' to allow for resolving potential circular references");
  55. }
  56. addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
  57. }
  58. // Initialize the bean instance.
  59. Object exposedObject = bean;
  60. try {
  61. // 2、装载属性,关键一步
  62. populateBean(beanName, mbd, instanceWrapper);
  63. // 3、调用初始化方法,应用BeanPostProcess后置处理器
  64. exposedObject = initializeBean(beanName, exposedObject, mbd);
  65. }
  66. catch (Throwable ex) {
  67. if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
  68. throw (BeanCreationException) ex;
  69. }
  70. else {
  71. throw new BeanCreationException(
  72. mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
  73. }
  74. }
  75. if (earlySingletonExposure) {
  76. Object earlySingletonReference = getSingleton(beanName, false);
  77. if (earlySingletonReference != null) {
  78. if (exposedObject == bean) {
  79. exposedObject = earlySingletonReference;
  80. }
  81. else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
  82. String[] dependentBeans = getDependentBeans(beanName);
  83. Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
  84. for (String dependentBean : dependentBeans) {
  85. if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
  86. actualDependentBeans.add(dependentBean);
  87. }
  88. }
  89. if (!actualDependentBeans.isEmpty()) {
  90. throw new BeanCurrentlyInCreationException(beanName,
  91. "Bean with name '" + beanName + "' has been injected into other beans [" +
  92. StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
  93. "] in its raw version as part of a circular reference, but has eventually been " +
  94. "wrapped. This means that said other beans do not use the final version of the " +
  95. "bean. This is often the result of over-eager type matching - consider using " +
  96. "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
  97. }
  98. }
  99. }
  100. }
  101. // Register bean as disposable.
  102. try {
  103. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  104. }
  105. catch (BeanDefinitionValidationException ex) {
  106. throw new BeanCreationException(
  107. mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  108. }
  109. return exposedObject;
  110. }

调用初始化方法,调用BeanPostProcess后置处理器

  1. /**
  2. * Initialize the given bean instance, applying factory callbacks
  3. * as well as init methods and bean post processors.
  4. * <p>Called from {@link #createBean} for traditionally defined beans,
  5. * and from {@link #initializeBean} for existing bean instances.
  6. * @param beanName the bean name in the factory (for debugging purposes)
  7. * @param bean the new bean instance we may need to initialize
  8. * @param mbd the bean definition that the bean was created with
  9. * (can also be {@code null}, if given an existing bean instance)
  10. * @return the initialized bean instance (potentially wrapped)
  11. * @see BeanNameAware
  12. * @see BeanClassLoaderAware
  13. * @see BeanFactoryAware
  14. * @see #applyBeanPostProcessorsBeforeInitialization
  15. * @see #invokeInitMethods
  16. * @see #applyBeanPostProcessorsAfterInitialization
  17. */
  18. protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
  19. if (System.getSecurityManager() != null) {
  20. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
  21. invokeAwareMethods(beanName, bean);
  22. return null;
  23. }, getAccessControlContext());
  24. }
  25. else {
  26. invokeAwareMethods(beanName, bean);
  27. }
  28. Object wrappedBean = bean;
  29. if (mbd == null || !mbd.isSynthetic()) {
  30. // 调用每一个后置处理器(BeanPostProcessor)的postProcessBeforeInitialization方法
  31. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  32. }
  33. try {
  34. // 开始执⾏afterPropertiesSet(实现了InitializingBean接⼝)⽅法和initMethod
  35. invokeInitMethods(beanName, wrappedBean, mbd);
  36. }
  37. catch (Throwable ex) {
  38. throw new BeanCreationException(
  39. (mbd != null ? mbd.getResourceDescription() : null),
  40. beanName, "Invocation of init method failed", ex);
  41. }
  42. if (mbd == null || !mbd.isSynthetic()) {
  43. // 执行每一个 BeanPostProcessor 的 postProcessAfterInitialization 方法
  44. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  45. }
  46. return wrappedBean;
  47. }

后置处理器

往下跟,看看后置处理器,是怎么执行每一个 BeanPostProcessor 的 postProcessAfterInitialization ?

  1. @Override
  2. public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
  3. throws BeansException {
  4. Object result = existingBean;
  5. for (BeanPostProcessor processor : getBeanPostProcessors()) {
  6. // 调用每一个BeanPostProcessor的postProcessAfterInitialization
  7. Object current = processor.postProcessAfterInitialization(result, beanName);
  8. if (current == null) {
  9. return result;
  10. }
  11. result = current;
  12. }
  13. return result;
  14. }

{@link org.springframework.aop.framework.autoproxy.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) throws BeansException {
  8. if (bean != null) {
  9. Object cacheKey = getCacheKey(bean.getClass(), beanName);
  10. // 缓存 earlyProxyReferences
  11. if (this.earlyProxyReferences.remove(cacheKey) != bean) {
  12. // 往下跟,封装返回代理类
  13. return wrapIfNecessary(bean, beanName, cacheKey);
  14. }
  15. }
  16. return bean;
  17. }

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. if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
  10. return bean;
  11. }
  12. if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
  13. return bean;
  14. }
  15. if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
  16. this.advisedBeans.put(cacheKey, Boolean.FALSE);
  17. return bean;
  18. }
  19. // Create proxy if we have advice.
  20. //返回当前bean的advisor、advice、interceptor
  21. Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
  22. if (specificInterceptors != DO_NOT_PROXY) {
  23. this.advisedBeans.put(cacheKey, Boolean.TRUE);
  24. // 重点在这,创建代理
  25. // 两种方式:CGLIB动态代理和JDK代理
  26. Object proxy = createProxy(
  27. bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
  28. this.proxyTypes.put(cacheKey, proxy.getClass());
  29. return proxy;
  30. }
  31. this.advisedBeans.put(cacheKey, Boolean.FALSE);
  32. return bean;
  33. }

createProxy过程

代理对象由createProxy方法创建,具体继续跟源码:

  1. /**
  2. * Create an AOP proxy for the given bean.
  3. * @param beanClass the class of the bean
  4. * @param beanName the name of the bean
  5. * @param specificInterceptors the set of interceptors that is
  6. * specific to this bean (may be empty, but not null)
  7. * @param targetSource the TargetSource for the proxy,
  8. * already pre-configured to access the bean
  9. * @return the AOP proxy for the bean
  10. * @see #buildAdvisors
  11. */
  12. protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
  13. @Nullable Object[] specificInterceptors, TargetSource targetSource) {
  14. if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
  15. AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
  16. }
  17. // 创建ProxyFactory实例,创建AopProxy工作交给ProxyFactory
  18. ProxyFactory proxyFactory = new ProxyFactory();
  19. proxyFactory.copyFrom(this);
  20. // proxyTargetClass = false 默认不开启,默认是使用JDK代理的
  21. // @EnableAspectJAutoProxy(proxyTargetClass = false) 或者 <aop:config proxy-target-class="false">
  22. if (!proxyFactory.isProxyTargetClass()) {
  23. if (shouldProxyTargetClass(beanClass, beanName)) {
  24. // 实现ConfigurableListableBeanFactory接口,
  25. // 而且org.springframework.aop.TargetSource#@see shouldProxyTargetClass返回true
  26. proxyFactory.setProxyTargetClass(true);
  27. }
  28. else {
  29. // 两种情况:1、有接口的,调用一次或多次:proxyFactory.addInterface(ifc);
  30. // 2. 没有接口的,调用:proxyFactory.setProxyTargetClass(true);
  31. evaluateProxyInterfaces(beanClass, proxyFactory);
  32. }
  33. }
  34. // 构建当前 bean 的 advisors 数组,把指定和通⽤拦截对象合并, 并都适配成Advisor
  35. Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
  36. proxyFactory.addAdvisors(advisors);
  37. // 设置参数
  38. proxyFactory.setTargetSource(targetSource);
  39. customizeProxyFactory(proxyFactory);
  40. proxyFactory.setFrozen(this.freezeProxy);
  41. if (advisorsPreFiltered()) {
  42. proxyFactory.setPreFiltered(true);
  43. }
  44. // 通过proxyFactory获取代理对象,开始创建AopProxy工作
  45. return proxyFactory.getProxy(getProxyClassLoader());
  46. }

ok,跟到这里,已经知道了一条信息代理对象是给ProxyFactory创建的

AopProxy创建

next,看看aopProxy怎么创建的

  1. /**
  2. * Create a new proxy according to the settings in this factory.
  3. * <p>Can be called repeatedly. Effect will vary if we've added
  4. * or removed interfaces. Can add and remove interceptors.
  5. * <p>Uses the given class loader (if necessary for proxy creation).
  6. * @param classLoader the class loader to create the proxy with
  7. * (or {@code null} for the low-level proxy facility's default)
  8. * @return the proxy object
  9. */
  10. public Object getProxy(@Nullable ClassLoader classLoader) {
  11. return createAopProxy().getProxy(classLoader);
  12. }

createAopProxy:

  1. /**
  2. * Subclasses should call this to get a new AOP proxy. They should <b>not</b>
  3. * create an AOP proxy with {@code this} as an argument.
  4. */
  5. protected final synchronized AopProxy createAopProxy() {
  6. if (!this.active) {
  7. activate();
  8. }
  9. // 通过AopProxyFactory创建AopProxy
  10. return getAopProxyFactory().createAopProxy(this);
  11. }

getAopProxyFactory返回的是DefaultAopProxyFactory
在这里插入图片描述
在这里插入图片描述
两个重要的代理对象:JdkDynamicAopProxy、ObjenesisCglibAopProxy
在这里插入图片描述
在这里插入图片描述

  1. public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
  2. @Override
  3. public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
  4. if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
  5. Class<?> targetClass = config.getTargetClass();
  6. if (targetClass == null) {
  7. throw new AopConfigException("TargetSource cannot determine target class: " +
  8. "Either an interface or a target is required for proxy creation.");
  9. }
  10. // 是接口(Interface)或者什么参数都不设置的情况使用JDK动态代理
  11. if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
  12. return new JdkDynamicAopProxy(config);
  13. }
  14. // 不是接口 proxyTargetClass为true的情况才使用CGLIB动态代理
  15. return new ObjenesisCglibAopProxy(config);
  16. }
  17. else {
  18. // JDK动态代理(默认)
  19. return new JdkDynamicAopProxy(config);
  20. }
  21. }
  22. /**
  23. * Determine whether the supplied {@link AdvisedSupport} has only the
  24. * {@link org.springframework.aop.SpringProxy} interface specified
  25. * (or no proxy interfaces specified at all).
  26. */
  27. private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
  28. Class<?>[] ifcs = config.getProxiedInterfaces();
  29. return (ifcs.length == 0 || (ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0])));
  30. }
  31. }

作用情况:

  • 是接口(Interface)或者什么参数都不设置的情况使用JDK动态代理
  • 不是接口 proxyTargetClass为true的情况才使用CGLIB动态代理

    创建AOP代理对象

    往回看AopProxy是怎么创建代理对象的 ``` /**
    • Create a new proxy according to the settings in this factory.
    • Can be called repeatedly. Effect will vary if we’ve added

    • or removed interfaces. Can add and remove interceptors.
    • Uses the given class loader (if necessary for proxy creation).

    • @param classLoader the class loader to create the proxy with
    • (or {@code null} for the low-level proxy facility’s default)
    • @return the proxy object */ public Object getProxy(@Nullable ClassLoader classLoader) { // ⽤ProxyFactory创建AopProxy, 然后⽤AopProxy创建Proxy return createAopProxy().getProxy(classLoader); }
  1. > Spring AOP的两张重要代理:JDK动态代理、CGLIB动态代理
  2. ![在这里插入图片描述](.%5Cimages%5C20201201101006807.png)
  3. ## JDK动态代理
  4. `{@link org.springframework.aop.framework.JdkDynamicAopProxy#getProxy(java.lang.ClassLoader)}`

@Override public Object getProxy(@Nullable ClassLoader classLoader) { if (logger.isDebugEnabled()) { logger.debug(“Creating JDK dynamic proxy: target source is “ + this.advised.getTargetSource()); } Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true); findDefinedEqualsAndHashCodeMethods(proxiedInterfaces); // 获取代理实例 调用了JDK API进行newProxyInstance,创建实例, // 参数:① classLoader,类加载实例 ② proxiedInterfaces,表示需要实现哪些接口 // ③ this,表示InvocationHandler,JdkDynamicAopProxy实现了InvocationHandler return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this); }

  1. ## CGLIB动态代理
  2. `{@link org.springframework.aop.framework.CglibAopProxy#getProxy(java.lang.ClassLoader)}`

@Override public Object getProxy(@Nullable ClassLoader classLoader) { if (logger.isDebugEnabled()) { logger.debug(“Creating CGLIB proxy: target source is “ + this.advised.getTargetSource()); }

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

}

``` 本文的代码例子可以在github找到下载链接:链接,SpringFramework代码中文注释,可以在我的github找到下载链接:链接
在这里插入图片描述