• 18-Spring AOP源码分析-AOP与BeanPostProcessor处理器


    专栏目录

    1. 1-Spring架构源码分析-Spring源码搭建
    2. 2-Spring架构源码分析-SSM框架说明
    3. 3-Spring架构源码分析-spring体系
    4. 4-Spring架构源码分析-Spring IOC机制设计思想和源码解读
    5. 5-Spring架构源码分析-Spring IOC之 Spring 统一资源加载策略
    6. 6-Spring架构源码分析-IoC 之加载 BeanDefinition
    7. 7-Spring架构源码分析-IoC 之注册 BeanDefinitions
    8. 8-Spring架构源码分析-IoC 之解析Bean:解析 import 标签
    9. 9-Spring架构源码分析-IoC 之解析 bean 标签:开启解析进程
    10. 10-Spring架构源码分析-IoC 之解析 bean标签:BeanDefinition
    11. 11-Spring架构源码分析-IoC 之注册解析的 BeanDefinitions
    12. 12-Spring架构源码分析-IoC 之装载 BeanDefinitions 总结
    13. 13-Spring架构源码分析-IoC 之开启 Bean 的加载
    14. 14-Spring架构源码分析-IoC 之加载 Bean:总结
    15. 15-Spring架构源码分析-Spring代理与AOP
    16. 16-Spring AOP源码分析-@EnableAspectJAutoProxy和AspectJAutoProxyRegistrar
    17. 17-Spring AOP源码分析-AnnotationAwareAspectJAutoProxyCreator
    18. 18-Spring AOP源码分析-AOP与BeanPostProcessor处理器
    19. 19-Spring AOP源码分析-代理对象调用目标方法
    20. 20-spring mvc设计思想和源码解读-spring mvc 功能特性
    21. 21-mvc 体系结构源码详解
    22. 22-Spring MVC源码跟踪
    23. 23-Spring事务源码分析
    BeanPostProcessor处理器

    4)真正的创建代理对象从BeanPostProcessor处理器的后置方法开始

    1:>org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessAfterInitialization

    2:>org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary 有必要的话进行包装

    3:>org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#getAdvicesAndAdvisorsForBean

    4:>org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#findEligibleAdvisors

    5:>org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#findAdvisorsThatCanApply

    6:>org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#createProxy创建代理对象

    4.1)*1:>org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessAfterInitialization源码分析*

    	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    		if (bean != null) {
    			//通过传入的class 和beanName生成缓存key
    			Object cacheKey = getCacheKey(bean.getClass(), beanName);
    			if (!this.earlyProxyReferences.contains(cacheKey)) {
    			    //若当前bean合适被包装为代理bean就进行处理
    				return wrapIfNecessary(bean, beanName, cacheKey);
    			}
    		}
    		return bean;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    4.2)*2:>org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary源码分析*

    	protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
    		//已经被处理过的 不进行下面的处理
    		if (beanName != null && this.targetSourcedBeans.contains(beanName)) {
    			return bean;
    		}
    		//不需要被增强的直接返回
    		if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
    			return bean;
    		}
    		//判断当前bean是不是基础类型的bean,或者指定类型的bean 不需要代理
    		if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
    			this.advisedBeans.put(cacheKey, Boolean.FALSE);
    			return bean;
    		}
    
    		//获取通知或者增强器
    		Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
    		//获取的不为空,生成代理对象
    		if (specificInterceptors != DO_NOT_PROXY) {
    			this.advisedBeans.put(cacheKey, Boolean.TRUE);
    			//创建代理对象
    			Object proxy = createProxy(
    					bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
    			this.proxyTypes.put(cacheKey, proxy.getClass());
    			return proxy;
    		}
            //加入advisedBeans集合中 
    		this.advisedBeans.put(cacheKey, Boolean.FALSE);
    		return bean;
    	}
    
    /**
     * 判断什么是基础的class
     * */
    protected boolean isInfrastructureClass(Class beanClass) {
    		//判断当前的class是不是 Pointcut Advisor   Advice  AopInfrastructureBean 只要有一个满足就返回true
    		boolean retVal = Advice.class.isAssignableFrom(beanClass) ||
    				Pointcut.class.isAssignableFrom(beanClass) ||
    				Advisor.class.isAssignableFrom(beanClass) ||
    				AopInfrastructureBean.class.isAssignableFrom(beanClass);
    		if (retVal && logger.isTraceEnabled()) {
    			logger.trace("Did not attempt to auto-proxy infrastructure class [" + beanClass.getName() + "]");
    		}
    		return retVal;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    4.3:>org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#getAdvicesAndAdvisorsForBean 源码分析

    	//找到符合条件的增强器 
    	@Override
    	protected Object[] getAdvicesAndAdvisorsForBean(Class beanClass, String beanName, TargetSource targetSource) {
    		//查找符合条件的增强器
    		List advisors = findEligibleAdvisors(beanClass, beanName);
    		if (advisors.isEmpty()) {
    			return DO_NOT_PROXY;
    		}
    		return advisors.toArray();
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    *4.4)org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#findEligibleAdvisors*

    	protected List findEligibleAdvisors(Class beanClass, String beanName) {
    		//找到候选的增强器
    		List candidateAdvisors = findCandidateAdvisors();
    		//从候选的中选出能用的增强器
    		List eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
    		extendAdvisors(eligibleAdvisors);
    		if (!eligibleAdvisors.isEmpty()) {
    			eligibleAdvisors = sortAdvisors(eligibleAdvisors);
    		}
    		return eligibleAdvisors;
    	}
    	
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    4.5)org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#findCandidateAdvisors 从IOC容器中查找所有的增强器

    	protected List findCandidateAdvisors() {
    	    //调用父类获取增强器
    		List advisors = super.findCandidateAdvisors();
    		//解析 @Aspect 注解,并构建通知器
    		advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
    		return advisors;
    	}
    	
    	
    =========================================super.findCandidateAdvisors();=================================
    	public List findAdvisorBeans() {
    		//先从缓存中获取增强器   cachedAdvisorBeanNames是advisor的名称
    		String[] advisorNames = this.cachedAdvisorBeanNames;
    		//缓存中没有获取到
    		if (advisorNames == null) {
    			//从IOC容器中获取增强器的名称
    			advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
    					this.beanFactory, Advisor.class, true, false);
    			//赋值给增强器缓存
    			this.cachedAdvisorBeanNames = advisorNames;
    		}
    		//在IOC容器中没有获取到直接返回
    		if (advisorNames.length == 0) {
    			return new ArrayList();
    		}
            
    		List advisors = new ArrayList();
    		//遍历所有的增强器
    		for (String name : advisorNames) {
    			if (isEligibleBean(name)) {
    				//忽略正在创建的增强器
    				if (this.beanFactory.isCurrentlyInCreation(name)) {
    					if (logger.isDebugEnabled()) {
    						logger.debug("Skipping currently created advisor '" + name + "'");
    					}
    				}
    				else {
    					try {
    					    //通过getBean的形式创建增强器 //并且将bean 添加到advisors中
    						advisors.add(this.beanFactory.getBean(name, Advisor.class));
    					}
    					catch (BeanCreationException ex) {
    						Throwable rootCause = ex.getMostSpecificCause();
    						if (rootCause instanceof BeanCurrentlyInCreationException) {
    							BeanCreationException bce = (BeanCreationException) rootCause;
    							if (this.beanFactory.isCurrentlyInCreation(bce.getBeanName())) {
    								if (logger.isDebugEnabled()) {
    									logger.debug("Skipping advisor '" + name +
    											"' with dependency on currently created bean: " + ex.getMessage());
    								}
    								// Ignore: indicates a reference back to the bean we're trying to advise.
    								// We want to find advisors other than the currently created bean itself.
    								continue;
    							}
    						}
    						throw ex;
    					}
    				}
    			}
    		}
    		return advisors;
    	}
    	
    =============================================aspectJAdvisorsBuilder.buildAspectJAdvisors()解析@Aspject的=======================================	
    下面buildAspectJAdvisors这个方法为我们做了什么? 
    第一步:先从增强器缓存中获取增强器对象
      判断缓存中有没有增强器对象,有,那么直接从缓存中直接获取返回出去
      没有.....从容器中获取所有的beanName
      遍历上一步获取所有的beanName,通过beanName获取beanType
      根据beanType判断当前bean是否是一个的Aspect注解类,若不是则不做任何处理
      调用advisorFactory.getAdvisors获取通知器
    
      
    
    	public List buildAspectJAdvisors() {
    		//先从缓存中获取
    		List aspectNames = this.aspectBeanNames;
    		//缓存中没有获取到
    		if (aspectNames == null) {
    			synchronized (this) {
    			    //在尝试从缓存中获取一次
    				aspectNames = this.aspectBeanNames;
    				//还是没有获取到
    				if (aspectNames == null) {
    					//从容器中获取所有的bean的name 
    					List advisors = new LinkedList();
    					aspectNames = new LinkedList();
    					String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
    							this.beanFactory, Object.class, true, false);
    					
    					//遍历beanNames		
    					for (String beanName : beanNames) {
    						if (!isEligibleBean(beanName)) {
    							continue;
    						}
    						//根据beanName获取bean的类型
    						Class beanType = this.beanFactory.getType(beanName);
    						if (beanType == null) {
    							continue;
    						}
    						//检查beanType是否包含Aspect
    						if (this.advisorFactory.isAspect(beanType)) {
    							aspectNames.add(beanName);
    							//创建一饿Aspect类的源信息对象
    							AspectMetadata amd = new AspectMetadata(beanType, beanName);
    							if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
    								MetadataAwareAspectInstanceFactory factory =
    										new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
    								//从aspectj中获取通知器
    								List classAdvisors = this.advisorFactory.getAdvisors(factory);
    								if (this.beanFactory.isSingleton(beanName)) {
    									this.advisorsCache.put(beanName, classAdvisors);
    								}
    								else {
    									this.aspectFactoryCache.put(beanName, factory);
    								}
    								advisors.addAll(classAdvisors);
    							}
    							else {
    								// Per target or per this.
    								if (this.beanFactory.isSingleton(beanName)) {
    									throw new IllegalArgumentException("Bean with name '" + beanName +
    											"' is a singleton, but aspect instantiation model is not singleton");
    								}
    								MetadataAwareAspectInstanceFactory factory =
    										new PrototypeAspectInstanceFactory(this.beanFactory, beanName);
    								this.aspectFactoryCache.put(beanName, factory);
    								advisors.addAll(this.advisorFactory.getAdvisors(factory));
    							}
    						}
    					}
    					this.aspectBeanNames = aspectNames;
    					return advisors;
    				}
    			}
    		}
            
            //返回空
    		if (aspectNames.isEmpty()) {
    			return Collections.emptyList();
    		}
    		//缓存中有增强器,我们从缓存中获取返回出去
    		List advisors = new LinkedList();
    		for (String aspectName : aspectNames) {
    			List cachedAdvisors = this.advisorsCache.get(aspectName);
    			if (cachedAdvisors != null) {
    				advisors.addAll(cachedAdvisors);
    			}
    			else {
    				MetadataAwareAspectInstanceFactory factory = this.aspectFactoryCache.get(aspectName);
    				advisors.addAll(this.advisorFactory.getAdvisors(factory));
    			}
    		}
    		return advisors;
    	}
    	
    
    //获取通知	
    ===========org.springframework.aop.aspectj.annotation.AspectJAdvisorFactory#getAdvisors========
    /**
     * 
     * 
     * */
    
    	public List getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) {
    		//获取标识了@AspectJ标志的切面类
    		Class aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
    		//获取切面的名称
    		String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName();
    		validate(aspectClass);
    
    		// We need to wrap the MetadataAwareAspectInstanceFactory with a decorator
    		// so that it will only instantiate once.
    		MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory =
    				new LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory);
            
    		List advisors = new ArrayList();
    		//获取切面类排除@PointCut标志的所有方法
    		for (Method method : getAdvisorMethods(aspectClass)) {
    			//每一个方法都调用getAdvisor方法来获取增强器
    			Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, advisors.size(), aspectName);
    			if (advisor != null) {
    				advisors.add(advisor);
    			}
    		}
    
    		// If it's a per target aspect, emit the dummy instantiating aspect.
    		if (!advisors.isEmpty() && lazySingletonAspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {
    			Advisor instantiationAdvisor = new SyntheticInstantiationAdvisor(lazySingletonAspectInstanceFactory);
    			advisors.add(0, instantiationAdvisor);
    		}
    
    		// Find introduction fields.
    		for (Field field : aspectClass.getDeclaredFields()) {
    			Advisor advisor = getDeclareParentsAdvisor(field);
    			if (advisor != null) {
    				advisors.add(advisor);
    			}
    		}
    
    		return advisors;
    	}
    	
    	
    //通过方法获取增强器	
    public Advisor getAdvisor(Method candidateAdviceMethod, MetadataAwareAspectInstanceFactory aspectInstanceFactory,
    			int declarationOrderInAspect, String aspectName) {
    
    		validate(aspectInstanceFactory.getAspectMetadata().getAspectClass());
            
            //获取aspectj的切点表达式
    		AspectJExpressionPointcut expressionPointcut = getPointcut(
    				candidateAdviceMethod, aspectInstanceFactory.getAspectMetadata().getAspectClass());
    		if (expressionPointcut == null) {
    			return null;
    		}
            
            //创建advisor实现类
    		return new InstantiationModelAwarePointcutAdvisorImpl(expressionPointcut, candidateAdviceMethod,
    				this, aspectInstanceFactory, declarationOrderInAspect, aspectName);
    }
    
    //获取切点表达式
    private AspectJExpressionPointcut getPointcut(Method candidateAdviceMethod, Class candidateAspectClass) {
    		//获取切面注解 @Before   @After。。。。。。
    		AspectJAnnotation aspectJAnnotation =
    				AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);
    		if (aspectJAnnotation == null) {
    			return null;
    		}
            
            //获取切点表达式对象
    		AspectJExpressionPointcut ajexp =
    				new AspectJExpressionPointcut(candidateAspectClass, new String[0], new Class[0]);
    		//设置切点表达式
    		ajexp.setExpression(aspectJAnnotation.getPointcutExpression());
    		ajexp.setBeanFactory(this.beanFactory);
    		return ajexp;
    	}
    	
    //找到切面类中方法上的切面注解	
    protected static AspectJAnnotation findAspectJAnnotationOnMethod(Method method) {
            //Pointcut.class, Around.class, Before.class, After.class, AfterReturning.class, AfterThrowing.class
    		for (Class clazz : ASPECTJ_ANNOTATION_CLASSES) {
    			AspectJAnnotation foundAnnotation = findAnnotation(method, (Class) clazz);
    			if (foundAnnotation != null) {
    				return foundAnnotation;
    			}
    		}
    		return null;
    	}
    	
    //把切点,候选的方法....统一处理生成一个增强器
    public InstantiationModelAwarePointcutAdvisorImpl(AspectJExpressionPointcut declaredPointcut,
    			Method aspectJAdviceMethod, AspectJAdvisorFactory aspectJAdvisorFactory,
    			MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrder, String aspectName) {
    
    		this.declaredPointcut = declaredPointcut;
    		this.declaringClass = aspectJAdviceMethod.getDeclaringClass();
    		this.methodName = aspectJAdviceMethod.getName();
    		this.parameterTypes = aspectJAdviceMethod.getParameterTypes();
    		this.aspectJAdviceMethod = aspectJAdviceMethod;
    		this.aspectJAdvisorFactory = aspectJAdvisorFactory;
    		this.aspectInstanceFactory = aspectInstanceFactory;
    		this.declarationOrder = declarationOrder;
    		this.aspectName = aspectName;
    
    		if (aspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {
    			// Static part of the pointcut is a lazy type.
    			Pointcut preInstantiationPointcut = Pointcuts.union(
    					aspectInstanceFactory.getAspectMetadata().getPerClausePointcut(), this.declaredPointcut);
    
    			// Make it dynamic: must mutate from pre-instantiation to post-instantiation state.
    			// If it's not a dynamic pointcut, it may be optimized out
    			// by the Spring AOP infrastructure after the first evaluation.
    			this.pointcut = new PerTargetInstantiationModelPointcut(
    					this.declaredPointcut, preInstantiationPointcut, aspectInstanceFactory);
    			this.lazy = true;
    		}
    		else {
    			// A singleton aspect.
    			this.pointcut = this.declaredPointcut;
    			this.lazy = false;
    			//实例化切面
    			this.instantiatedAdvice = instantiateAdvice(this.declaredPointcut);
    		}
    	}
    	
    //获取advice 切面对象	
    public Advice getAdvice(Method candidateAdviceMethod, AspectJExpressionPointcut expressionPointcut,
    			MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrder, String aspectName) {
            
            //获取候选的切面类
    		Class candidateAspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
    		validate(candidateAspectClass);
            
            //获取切面注解
    		AspectJAnnotation aspectJAnnotation =
    				AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);
    		if (aspectJAnnotation == null) {
    			return null;
    		}
    
    		// If we get here, we know we have an AspectJ method.
    		// Check that it's an AspectJ-annotated class
    		if (!isAspect(candidateAspectClass)) {
    			throw new AopConfigException("Advice must be declared inside an aspect type: " +
    					"Offending method '" + candidateAdviceMethod + "' in class [" +
    					candidateAspectClass.getName() + "]");
    		}
    
    		if (logger.isDebugEnabled()) {
    			logger.debug("Found AspectJ method: " + candidateAdviceMethod);
    		}
    
    		AbstractAspectJAdvice springAdvice;
            
            //判断注解的类型
    		switch (aspectJAnnotation.getAnnotationType()) {
    			//是切点的返回null
    			case AtPointcut:
    				if (logger.isDebugEnabled()) {
    					logger.debug("Processing pointcut '" + candidateAdviceMethod.getName() + "'");
    				}
    				return null;
    			//是不是环绕通知
    			case AtAround:
    				springAdvice = new AspectJAroundAdvice(
    						candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
    				break;
    			//是不是前置通知	
    			case AtBefore:
    				springAdvice = new AspectJMethodBeforeAdvice(
    						candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
    				break;
    			//是不是后置通知
    			case AtAfter:
    				springAdvice = new AspectJAfterAdvice(
    						candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
    				break;
    			//返回通知
    			case AtAfterReturning:
    				springAdvice = new AspectJAfterReturningAdvice(
    						candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
    				AfterReturning afterReturningAnnotation = (AfterReturning) aspectJAnnotation.getAnnotation();
    				if (StringUtils.hasText(afterReturningAnnotation.returning())) {
    					springAdvice.setReturningName(afterReturningAnnotation.returning());
    				}
    				break;
    			是不是异常通知	
    			case AtAfterThrowing:
    				springAdvice = new AspectJAfterThrowingAdvice(
    						candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
    				AfterThrowing afterThrowingAnnotation = (AfterThrowing) aspectJAnnotation.getAnnotation();
    				if (StringUtils.hasText(afterThrowingAnnotation.throwing())) {
    					springAdvice.setThrowingName(afterThrowingAnnotation.throwing());
    				}
    				break;
    			default:
    				throw new UnsupportedOperationException(
    						"Unsupported advice type on method: " + candidateAdviceMethod);
    		}
    
    		// Now to configure the advice...
    		springAdvice.setAspectName(aspectName);
    		springAdvice.setDeclarationOrder(declarationOrder);
        	/*
             * 获取方法的参数列表名称,比如方法 int sum(int numX, int numY), 
             * getParameterNames(sum) 得到 argNames = [numX, numY]
             */
    		String[] argNames = this.parameterNameDiscoverer.getParameterNames(candidateAdviceMethod);
    		if (argNames != null) {
    		    //为切面设置参数
    			springAdvice.setArgumentNamesFromStringArray(argNames);
    		}
    		springAdvice.calculateArgumentBindings();
    
    		return springAdvice;
    	}	
    	
    	
    	
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
    • 354
    • 355
    • 356
    • 357
    • 358
    • 359
    • 360
    • 361
    • 362
    • 363
    • 364
    • 365
    • 366
    • 367
    • 368
    • 369
    • 370
    • 371
    • 372
    • 373
    • 374
    • 375
    • 376
    • 377
    • 378
    • 379
    • 380
    • 381
    • 382

    4.6:)>org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#findAdvisorsThatCanApply

    	//获取能够使用的增强器
    	protected List findAdvisorsThatCanApply(
    			List candidateAdvisors, Class beanClass, String beanName) {
            
    		ProxyCreationContext.setCurrentProxiedBeanName(beanName);
    		try {
    			return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
    		}
    		finally {
    			ProxyCreationContext.setCurrentProxiedBeanName(null);
    		}
    	}
        
        //获取能使用的增强器
    	public static List findAdvisorsThatCanApply(List candidateAdvisors, Class clazz) {
    		if (candidateAdvisors.isEmpty()) {
    			return candidateAdvisors;
    		}
    		List eligibleAdvisors = new LinkedList();
    		//遍历候选的增强器 把他增加到eligibleAdvisors集合中返回
    		for (Advisor candidate : candidateAdvisors) {
    			if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
    				eligibleAdvisors.add(candidate);
    			}
    		}
    		boolean hasIntroductions = !eligibleAdvisors.isEmpty();
    		for (Advisor candidate : candidateAdvisors) {
    			if (candidate instanceof IntroductionAdvisor) {
    				// already processed
    				continue;
    			}
    			if (canApply(candidate, clazz, hasIntroductions)) {
    				eligibleAdvisors.add(candidate);
    			}
    		}
    		return eligibleAdvisors;
    	}	
    	
    	//判断是当前的增强器是否能用 通过方法匹配来计算当前是否合适当前类的增强器
    	public static boolean canApply(Advisor advisor, Class targetClass, boolean hasIntroductions) {
    		if (advisor instanceof IntroductionAdvisor) {
    			return ((IntroductionAdvisor) advisor).getClassFilter().matches(targetClass);
    		}
    		else if (advisor instanceof PointcutAdvisor) {
    			PointcutAdvisor pca = (PointcutAdvisor) advisor;
    			return canApply(pca.getPointcut(), targetClass, hasIntroductions);
    		}
    		else {
    			// It doesn't have a pointcut so we assume it applies.
    			return true;
    		}
    	}
    	
    
    
    	public static boolean canApply(Pointcut pc, Class targetClass, boolean hasIntroductions) {
    		Assert.notNull(pc, "Pointcut must not be null");
    		if (!pc.getClassFilter().matches(targetClass)) {
    			return false;
    		}
            
            //创建一个方法匹配器
    		MethodMatcher methodMatcher = pc.getMethodMatcher();
    		if (methodMatcher == MethodMatcher.TRUE) {
    			// No need to iterate the methods if we're matching any method anyway...
    			return true;
    		}
            
            //包装方法匹配器
    		IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
    		if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
    			introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
    		}
            
            //获取本来和接口
    		Set> classes = new LinkedHashSet>(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
    		classes.add(targetClass);
    		//循环classes
    		for (Class clazz : classes) {
    		    //获取所有的方法 进行匹配
    			Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
    			for (Method method : methods) {
    				if ((introductionAwareMethodMatcher != null &&
    						introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions)) ||
    						methodMatcher.matches(method, targetClass)) {
    					return true;
    				}
    			}
    		}
    
    		return false;
    	}	
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92

    4.5)org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#createProxy创建代理对象

    	protected Object createProxy(
    			Class beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) {
            
            //判断容器的类型ConfigurableListableBeanFactory
    		if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
    			AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
    		}
            
            //创建代理工程
    		ProxyFactory proxyFactory = new ProxyFactory();
    		proxyFactory.copyFrom(this);
            
            
            /*
             * 默认配置下,或用户显式配置 proxy-target-class = "false" 时,
             * 这里的 proxyFactory.isProxyTargetClass() 也为 false
             */
    		if (!proxyFactory.isProxyTargetClass()) {
    			if (shouldProxyTargetClass(beanClass, beanName)) {
    				proxyFactory.setProxyTargetClass(true);
    			}
    			
    			else {
    			    /*
                 * 检测 beanClass 是否实现了接口,若未实现,则将 
                 * proxyFactory 的成员变量 proxyTargetClass 设为 true
                 */
    				evaluateProxyInterfaces(beanClass, proxyFactory);
    			}
    		}
            
            //获取容器中的方法增强器
    		Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
    		proxyFactory.addAdvisors(advisors);
    		proxyFactory.setTargetSource(targetSource);
    		customizeProxyFactory(proxyFactory);
    
    		proxyFactory.setFrozen(this.freezeProxy);
    		if (advisorsPreFiltered()) {
    			proxyFactory.setPreFiltered(true);
    		}
            
            //创建代理对象
    		return proxyFactory.getProxy(getProxyClassLoader());
    	}
    	
    	public Object getProxy(ClassLoader classLoader) {
    		return createAopProxy().getProxy(classLoader);
    	}
    	
    	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() || Proxy.isProxyClass(targetClass)) {
    			    //jdk代理
    				return new JdkDynamicAopProxy(config);
    			}
    			//cglib代理
    			return new ObjenesisCglibAopProxy(config);
    		}
    		else {
    		    jdk代理
    			return new JdkDynamicAopProxy(config);
    		}
    	}
    	
    	public Object getProxy(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代理对象
    		return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
    	}
    	
    	
    	
    	
    	
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85

    专栏目录

    1. 1-Spring架构源码分析-Spring源码搭建
    2. 2-Spring架构源码分析-SSM框架说明
    3. 3-Spring架构源码分析-spring体系
    4. 4-Spring架构源码分析-Spring IOC机制设计思想和源码解读
    5. 5-Spring架构源码分析-Spring IOC之 Spring 统一资源加载策略
    6. 6-Spring架构源码分析-IoC 之加载 BeanDefinition
    7. 7-Spring架构源码分析-IoC 之注册 BeanDefinitions
    8. 8-Spring架构源码分析-IoC 之解析Bean:解析 import 标签
    9. 9-Spring架构源码分析-IoC 之解析 bean 标签:开启解析进程
    10. 10-Spring架构源码分析-IoC 之解析 bean标签:BeanDefinition
    11. 11-Spring架构源码分析-IoC 之注册解析的 BeanDefinitions
    12. 12-Spring架构源码分析-IoC 之装载 BeanDefinitions 总结
    13. 13-Spring架构源码分析-IoC 之开启 Bean 的加载
    14. 14-Spring架构源码分析-IoC 之加载 Bean:总结
    15. 15-Spring架构源码分析-Spring代理与AOP
    16. 16-Spring AOP源码分析-@EnableAspectJAutoProxy和AspectJAutoProxyRegistrar
    17. 17-Spring AOP源码分析-AnnotationAwareAspectJAutoProxyCreator
    18. 18-Spring AOP源码分析-AOP与BeanPostProcessor处理器
    19. 19-Spring AOP源码分析-代理对象调用目标方法
    20. 20-spring mvc设计思想和源码解读-spring mvc 功能特性
    21. 21-mvc 体系结构源码详解
    22. 22-Spring MVC源码跟踪
    23. 23-Spring事务源码分析
  • 相关阅读:
    12个MySQL慢查询的原因分析
    Activiti回退与跳转节点
    [贪心算法]Leetcode738. 单调递增的数字
    Java设计模式之解释器模式
    Spring frame :基于 jdk 动态代理实现连接池复用
    【服务器数据恢复】hp服务器raid5磁盘掉线导致raid5不可用的数据恢复案例
    GIT使用
    语法练习:front_back
    一般香港服务器带宽选多大够用?(带宽计算方法)
    习题:数组(二)
  • 原文地址:https://blog.csdn.net/xianghanscce/article/details/126497035