spring aop源码分析

spring初始化源码分析这章中已经介绍过bean的详细初始化流程,所以我们知道bean在初始化之后会执行BeanPostProcessor的postProcessAfterInitialization方法,aop的实现原理就在BeanPostProcessor的后置处理方法当中,接下来我们详细分析aop的实现原理

1、启用aop我们需要标注@EnableAspectJAutoProxy注解,我们从@EnableAspectJAutoProxy注解进行分析,源码如下:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {

	// 指定使用cglib进行代理而不是使用jdk的Proxy,在AspectJAutoProxyRegistrar会被用来判断
	boolean proxyTargetClass() default false;

	 // 是否在执行时将代理对象放入ThreadLocal
	boolean exposeProxy() default false;

}

可以看见源码中有一个@Import(AspectJAutoProxyRegistrar.class),此处为核心,表明导入配置类AspectJAutoProxyRegistrar

2、接下来我们切入AspectJAutoProxyRegistrar中看看他具体做了什么事情
class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {

	@Override
	public void registerBeanDefinitions(
			AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		// 再容器注入一个beanName = org.springframework.aop.config.internalAutoProxyCreator,
		// class = AnnotationAwareAspectJAutoProxyCreator.class的bean
		AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);
		// 获取@EnableAspectJAutoProxy注解的属性值
		AnnotationAttributes enableAspectJAutoProxy =
				AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
		if (enableAspectJAutoProxy != null) {
			// 如果指定了proxyTargetClass = true,往beanName为 org.springframework.aop.config.internalAutoProxyCreator的bean中注入proxyTargetClass = true
			if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
				AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
			}
			// 如果指定了exposeProxy= true,往beanName为 org.springframework.aop.config.internalAutoProxyCreator的bean中注入exposeProxy = true
			if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
				AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
			}
		}
	}

}
3、看看AnnotationAwareAspectJAutoProxyCreator到底是个什么东西

首先我们需要先看看AnnotationAwareAspectJAutoProxyCreator的继承关系,我们用流程图来展示他的继承关系
在这里插入图片描述
从图中可以看出AnnotationAwareAspectJAutoProxyCreator其实也是一个BeanPostProcessor,所以再bean初始化之后会调用到父类的AbstractAutoProxyCreator的postProcessAfterInitialization方法进行后置处理,aop的实现原理就在此后置处理中实现,下一步开始分析aop动态代理的实现

4、AbstractAutoProxyCreator.postProcessAfterInitialization方法源码分析
  • 1、AbstractAutoProxyCreator的后置处理方法
	@Override
	public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
		if (bean != null) {
			Object cacheKey = getCacheKey(bean.getClass(), beanName);
			if (this.earlyProxyReferences.remove(cacheKey) != bean) {
				// 核心方法,此方法进行动态代理
				return wrapIfNecessary(bean, beanName, cacheKey);
			}
		}
		return bean;
	}
  • wrapIfNecessary详细分析
	protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
		// 这三个if判断用来判断bean是否应该被创建动态代理
		// 如果beanName不是空,并且为当前对象自定义了TargetSource直接返回当前对象
		if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
			return bean;
		}
		// 如果当前bean被标记为不需要代理直接返回当前对象
		if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
			return bean;
		}
		// 如果当前bean是Advice、Pointcut、Advisor、AopInfrastructureBean中的任意子类则不会被代理
		// 如果当前bean是一个切面,不会被代理
		if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
			this.advisedBeans.put(cacheKey, Boolean.FALSE);
			return bean;
		}

		// 获取当前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;
		}
		// 标记此bean已被动态代理
		this.advisedBeans.put(cacheKey, Boolean.FALSE);
		return bean;
	}
  • createProxy详细分析
	protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
			@Nullable Object[] specificInterceptors, TargetSource targetSource) {
		// 在beanDifine中设置一个属性,key = org.springframework.aop.framework.autoproxy.AutoProxyUtils.originalTargetClass,value = 当前bean的class
		if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
			AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
		}
		// 构建代理工厂
		ProxyFactory proxyFactory = new ProxyFactory();
		// 将this中的一些核心属性的值赋值给proxyFactory 
		// proxyTargetClass、optimize、exposeProxy、frozen、opaque
		proxyFactory.copyFrom(this);
		if (!proxyFactory.isProxyTargetClass()) {
			if (shouldProxyTargetClass(beanClass, beanName)) {
				proxyFactory.setProxyTargetClass(true);
			}
			else {
				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 class DefaultAopProxyFactory implements AopProxyFactory, Serializable {

	@Override
	public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
		// isOptimize(是否对生成代理策略进行优化),true : 进行优化,如果有接口就代理接口(使用JDK动态代理),没有接口代理类(CGLIB代理)。默认值:false。
        // proxyTargetClass(是否强制使用CGLIB来实现代理),true : 强制使用CGLIB来实现代理,false : 不强制使用CGLIB来实现代理,首选JDK来实现代理,(默认值)
		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.");
			}
			// 如果是接口使用jdk动态代理
			if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
				return new JdkDynamicAopProxy(config);
			}
			// 如果不是接口使用cjlib代理
			return new ObjenesisCglibAopProxy(config);
		}
		else {
			return new JdkDynamicAopProxy(config);
		}
	}

	private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
		Class<?>[] ifcs = config.getProxiedInterfaces();
		return (ifcs.length == 0 || (ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0])));
	}
}
5、aop拦截方法执行流程
  • intercept
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
			Object oldProxy = null;
			boolean setProxyContext = false;
			Object target = null;
			TargetSource targetSource = this.advised.getTargetSource();
			try {
				if (this.advised.exposeProxy) {
					oldProxy = AopContext.setCurrentProxy(proxy);
					setProxyContext = true;
				}
				target = targetSource.getTarget();
				Class<?> targetClass = (target != null ? target.getClass() : null);
				// 获取当前方法的拦截器链
				List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
				Object retVal;
				// 如果拦截器链是空的,并且方法为public
				if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
					// 获取参数
					Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);				// 执行目标方法
					retVal = methodProxy.invoke(target, argsToUse);
				}
				else {
					// 否则从拦截器链依次进行执行
					retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
				}
				// 处理返回值
				retVal = processReturnType(proxy, target, method, retVal);
				return retVal;
			}
			finally {
				if (target != null && !targetSource.isStatic()) {
					targetSource.releaseTarget(target);
				}
				if (setProxyContext) {
					// Restore old proxy.
					AopContext.setCurrentProxy(oldProxy);
				}
			}
		}
  • proceed
	public Object proceed() throws Throwable {
		// this.currentInterceptorIndex默认值为-1 !!!
		//	如果当前下标是拦截器链的最后一位
		if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {		
			// 执行目标方法本身
			return invokeJoinpoint();
		}
		// 获取当前下标+1对应的拦截方法
		Object interceptorOrInterceptionAdvice =
				this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
		// 如果是拦截方法
		if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
			// 判断当前拦截方法是否应该拦截当前方法
			InterceptorAndDynamicMethodMatcher dm =
					(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
			Class<?> targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass());
			if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) {
				// 执行拦截方法的调用
				return dm.interceptor.invoke(this);
			}
			else {
				// 不匹配直接跳出,进行下一个拦截方法的判断
				return proceed();
			}
		}
		else {
			// 拦截器链的第一位是一个ExposeInvocationInterceptor,用来调用后续的拦截方法
			return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
		}
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值