代理对象的创建时机位于Bean的初始化之后,调用Bean的后置处理器AnnotationAwareAspectJAutoProxyCreatorpostProcessAfterInitialization方法

postProcessAfterInitialization

org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessAfterInitialization

  1. public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
  2. if (bean != null) {
  3. // 先从缓存中获取代理对象
  4. Object cacheKey = getCacheKey(bean.getClass(), beanName);
  5. if (this.earlyProxyReferences.remove(cacheKey) != bean) {
  6. // 按需生成代理对象
  7. return wrapIfNecessary(bean, beanName, cacheKey);
  8. }
  9. }
  10. return bean;
  11. }

按需生成代理对象,org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary

  1. protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
  2. if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
  3. return bean;
  4. }
  5. if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
  6. return bean;
  7. }
  8. if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
  9. this.advisedBeans.put(cacheKey, Boolean.FALSE);
  10. return bean;
  11. }
  12. // Create proxy if we have advice.
  13. /**
  14. * @see AbstractAdvisorAutoProxyCreator#getAdvicesAndAdvisorsForBean(java.lang.Class, java.lang.String, org.springframework.aop.TargetSource)
  15. */
  16. // 获取与当前Bean匹配的切面
  17. Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
  18. if (specificInterceptors != DO_NOT_PROXY) {
  19. this.advisedBeans.put(cacheKey, Boolean.TRUE);
  20. // 创建代理
  21. Object proxy = createProxy(
  22. bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
  23. this.proxyTypes.put(cacheKey, proxy.getClass());
  24. return proxy;
  25. }
  26. // 缓存
  27. this.advisedBeans.put(cacheKey, Boolean.FALSE);
  28. return bean;
  29. }

解析@Aspect注解,生成Advisor

找被切面增强的Advisor

  1. @Override
  2. @Nullable
  3. protected Object[] getAdvicesAndAdvisorsForBean(
  4. Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
  5. List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
  6. if (advisors.isEmpty()) {
  7. return DO_NOT_PROXY;
  8. }
  9. return advisors.toArray();
  10. }

AbstractAdvisorAutoProxyCreator#findEligibleAdvisors

  1. protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
  2. /**
  3. * @see AnnotationAwareAspectJAutoProxyCreator#findCandidateAdvisors()
  4. */
  5. // 获取容器中所有的切面Advisor
  6. // 这里返回的切面中的方法已经是有序的了,
  7. //先按注解顺序(Around.class, Before.class, After.class, AfterReturning.class, AfterThrowing.class),再按方法名称
  8. List<Advisor> candidateAdvisors = findCandidateAdvisors();
  9. // 获取所有能够作用于当前Bean上的Advisor
  10. List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
  11. /**
  12. * @see AspectJAwareAdvisorAutoProxyCreator#extendAdvisors(java.util.List)
  13. */
  14. // 往集合第一个位置加入了一个DefaultPointcutAdvisor
  15. extendAdvisors(eligibleAdvisors);
  16. if (!eligibleAdvisors.isEmpty()) {
  17. /**
  18. * @see AspectJAwareAdvisorAutoProxyCreator#sortAdvisors(java.util.List)
  19. */
  20. // 这里是对切面进行排序,例如有@Order注解或者实现了Ordered接口
  21. eligibleAdvisors = sortAdvisors(eligibleAdvisors);
  22. }
  23. return eligibleAdvisors;
  24. }

findCandidateAdvisors

  1. protected List<Advisor> findCandidateAdvisors() {
  2. // Add all the Spring advisors found according to superclass rules.
  3. // 获取容器中所有的切面Advisor
  4. List<Advisor> advisors = super.findCandidateAdvisors();
  5. // Build Advisors for all AspectJ aspects in the bean factory.
  6. if (this.aspectJAdvisorsBuilder != null) {
  7. // 这里还需要解析@Aspect注解,生成Advisor
  8. advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
  9. }
  10. return advisors;
  11. }

findAdvisorsThatCanApply

org.springframework.aop.support.AopUtils#findAdvisorsThatCanApply

  1. public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
  2. if (candidateAdvisors.isEmpty()) {
  3. return candidateAdvisors;
  4. }
  5. List<Advisor> eligibleAdvisors = new ArrayList<>();
  6. // InstantiationModelAwarePointcutAdvisorImpl
  7. for (Advisor candidate : candidateAdvisors) {
  8. if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
  9. // IntroductionAdvisor类型为引入切面,具体类型为DeclareParentsAdvisor
  10. eligibleAdvisors.add(candidate);
  11. }
  12. }
  13. boolean hasIntroductions = !eligibleAdvisors.isEmpty();
  14. for (Advisor candidate : candidateAdvisors) {
  15. if (candidate instanceof IntroductionAdvisor) {
  16. // already processed
  17. continue;
  18. }
  19. // PointCut中的ClassFilter.match 匹配类
  20. // PointCut中的MethodMatcher.match 匹配方法
  21. if (canApply(candidate, clazz, hasIntroductions)) {
  22. // @Aspect,类型为InstantiationModelAwarePointcutAdvisorImpl
  23. eligibleAdvisors.add(candidate);
  24. }
  25. }
  26. return eligibleAdvisors;
  27. }

创建代理对象

在为业务逻辑组件创建代理对象的时候,使用的是cglib来创建动态代理的。当然了,如果业务逻辑类有实现接口,那么就使用jdk来创建动态代理。

  1. protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
  2. @Nullable Object[] specificInterceptors, TargetSource targetSource) {
  3. if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
  4. AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
  5. }
  6. // 创建代理工厂
  7. ProxyFactory proxyFactory = new ProxyFactory();
  8. proxyFactory.copyFrom(this);
  9. if (!proxyFactory.isProxyTargetClass()) {
  10. // 进来说明proxyTargetClass=false,指定JDK代理
  11. if (shouldProxyTargetClass(beanClass, beanName)) {
  12. // 进来这里说明BD中有个属性preserveTargetClass=true,可以BD中属性设置的优先级最高
  13. proxyFactory.setProxyTargetClass(true);
  14. }
  15. else {
  16. // 这里会判断bean有没有实现接口,没有就只能使用CGlib
  17. evaluateProxyInterfaces(beanClass, proxyFactory);
  18. }
  19. }
  20. Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
  21. proxyFactory.addAdvisors(advisors); // 切面
  22. proxyFactory.setTargetSource(targetSource); // 目标对象
  23. customizeProxyFactory(proxyFactory);
  24. proxyFactory.setFrozen(this.freezeProxy);
  25. if (advisorsPreFiltered()) {
  26. proxyFactory.setPreFiltered(true);
  27. }
  28. // 使用JDK或者CGlib创建代理对象
  29. return proxyFactory.getProxy(getProxyClassLoader());
  30. }