Spring源码阅读 -- > SpringAOP代理对象创建流程

目录

1、AOP用例准备

2、观察断点,探究AOP代理对象的生成时机

3、代理对象创建流程源码分析

        3.1、开始创建代理对象节点

        3.1.1、initializeBean方法

        3.1.2、applyBeanPostProcessorsAfterInitialization方法

        3.1.3、postProcessAfterInitialization方法

        3.1.4、wrapIfNecessary方法

        3.1.5、createProxy方法

        3.1.6、proxyFactory.getProxy()

        3.1.7、createAopProxy方法 

        3.1.8、CglibAopProxy类的getProxy方法


1、AOP用例准备

        user类定义

package com.demo.spring;

import org.springframework.stereotype.Component;

@Component
public class User {

	public void outPut(){
		System.out.println("outPut----执行");
	}
}

        UserAspect切面类定义

package com.demo.spring.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class UserAspect {

	public void before(){
		System.out.println("aspect ---- before");
	}
}

         applicationContext.xml定义

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:aop="http://www.springframework.org/schema/aop"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xsi:schemaLocation="
	    http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
">

	<bean id="user" class="com.demo.spring.User"/>

	<!--aop配置-->
	<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

	<!--横切逻辑-->
	<bean id="userAspect" class="com.demo.spring.aspect.UserAspect"/>
    
	<aop:config>
		<aop:aspect ref="userAspect">
			<aop:before method="before" pointcut="execution(* com.demo.spring.*.*(..))"/>
		</aop:aspect>
	</aop:config>


</beans>

        测试方法

	@Test
	public void testAOP() {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
		User user = applicationContext.getBean(User.class);
		user.outPut();
	}

2、观察断点,探究AOP代理对象的生成时机

        可以发现,在getBean之前,user对象已经产生,并且该对象是一个代理对象(Cglib代理对象),故此,我们可以断定,目标Bean在容器初始化的时候已经完成了代理,实现了方法的增强。        

3、代理对象创建流程源码分析

        3.1、开始创建代理对象节点

               由之前的  SpringIOC Bean的创建流程 可以知道Bean是在AbstractAutowireCapableBeanFactory类中的doCreateBean方法中进行实例化,并且属性填充的,通过观察断点可以发现代理对象的生成是在initializeBean方法中

         3.1.1、initializeBean方法

        initializeBean方法主要是Bean的实现的声明周期相关接⼝的属性注⼊,这里面会执行BeanPostprocessor的前置方法,后置方法,AOP代理对象创建就是在BeanPostProcessor的后置方法中完成的。        

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
		// 执⾏所有的AwareMethods
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			// 执⾏所有的BeanPostProcessor#postProcessBeforeInitialization 初始化之前的处理器⽅法
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			// 这⾥就开始执⾏afterPropertiesSet(实现了InitializingBean接⼝)⽅法和initMethod
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					(mbd != null ? mbd.getResourceDescription() : null),
					beanName, "Invocation of init method failed", ex);
		}
		if (mbd == null || !mbd.isSynthetic()) {
			// 整个Bean初始化完成,执⾏后置处理器⽅法
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}

        3.1.2、applyBeanPostProcessorsAfterInitialization方法

        在该方法内会循环执行后置处理器,其中创建AOP代理对象的后置处理器为AbstractAutoProxyCreator的postProcessAfterInitialization方法

public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
			throws BeansException {

		Object result = existingBean;
//循环执⾏后置处理器
		for (BeanPostProcessor processor : getBeanPostProcessors()) {
			Object current = processor.postProcessAfterInitialization(result, beanName);
			if (current == null) {
				return result;
			}
			result = current;
		}
		return result;
	}

        3.1.3、postProcessAfterInitialization方法

        检查是否已经暴露过

public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
		if (bean != null) {
			// 检查下该类是否已经暴露过了(可能已经创建了,⽐如A依赖B时,创建A时候,就会先去创建B。
			// 当真正需要创建B时,就没必要再代理⼀次已经代理过的对象),避免重复创建
			Object cacheKey = getCacheKey(bean.getClass(), beanName);
			if (this.earlyProxyReferences.remove(cacheKey) != bean) {
				return wrapIfNecessary(bean, beanName, cacheKey);
			}
		}
		return bean;
	}

         3.1.4、wrapIfNecessary方法

         获取切入点与增强数组,存在需要对应切入点与增强方法则调用createProxy创建代理对象

	protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
		// targetSourcedBeans包含,说明前⾯创建过
		if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
			return bean;
		}
		if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
			return bean;
		}
		if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
			this.advisedBeans.put(cacheKey, Boolean.FALSE);
			return bean;
		}

		// 如果有增强方法,则创建代理对象
		// 得到所有候选Advisor,对Advisors和bean的⽅法双层遍历匹配,最终得到⼀个List<Advisor>,即specificInterceptors
		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;
		}

		this.advisedBeans.put(cacheKey, Boolean.FALSE);
		return bean;
	}

        3.1.5、createProxy方法

        为Bean创建指定代理对象

protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
			@Nullable Object[] specificInterceptors, TargetSource targetSource) {

		if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
			AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
		}
		// 创建代理的⼯作交给ProxyFactory
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.copyFrom(this);
		// 根据⼀些情况判断是否要设置proxyTargetClass=true
		if (!proxyFactory.isProxyTargetClass()) {
			if (shouldProxyTargetClass(beanClass, beanName)) {
				proxyFactory.setProxyTargetClass(true);
			}
			else {
				evaluateProxyInterfaces(beanClass, proxyFactory);
			}
		}
		// 把指定和通⽤拦截对象合并, 并都适配成Advisor
		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());
	}

         3.1.6、proxyFactory.getProxy()

        ⽤ProxyFactory创建AopProxy, 然后⽤AopProxy创建Proxy, 所以这⾥重要的是看获取的AopProxy对象是什么, 然后进去看怎么创建动态代理, 提供了两种:jdk proxy(有实现接口使用), cglib

	public Object getProxy(@Nullable ClassLoader classLoader) {
        // ⽤ProxyFactory创建AopProxy, 然后⽤AopProxy创建Proxy, 所以这⾥重要的是看获取的AopProxy对象是什么,
		// 然后进去看怎么创建动态代理, 提供了两种:jdk proxy, cglib
		return createAopProxy().getProxy(classLoader);
	}
protected final synchronized AopProxy createAopProxy() {
		if (!this.active) {
			activate();
		}
		//先获取创建AopProxy的⼯⼚, 再由此创建AopProxy
		return getAopProxyFactory().createAopProxy(this);
	}

        3.1.7、createAopProxy方法 

        具体流程就是⽤AopProxyFactory 创建 AopProxy, 再⽤ AopProxy 创建代理对象,这⾥的 AopProxyFactory 默认是DefaultAopProxyFactory ,看他的 createAopProxy ⽅法
public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {

	@Override
	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)) {
				return new JdkDynamicAopProxy(config);
			}
			return new ObjenesisCglibAopProxy(config);
		}
		else {
			return new JdkDynamicAopProxy(config);
		}
	}

	/**
	 * Determine whether the supplied {@link AdvisedSupport} has only the
	 * {@link org.springframework.aop.SpringProxy} interface specified
	 * (or no proxy interfaces specified at all).
	 */
	private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
		Class<?>[] ifcs = config.getProxiedInterfaces();
		return (ifcs.length == 0 || (ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0])));
	}

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

       3.1.8、CglibAopProxy类的getProxy方法

        该方法则是创建代理对象并返回创建好的代理对象,至此,AOP的代理对象创建完成。
public Object getProxy(@Nullable ClassLoader classLoader) {
		if (logger.isTraceEnabled()) {
			logger.trace("Creating CGLIB proxy: " + this.advised.getTargetSource());
		}

		try {
			Class<?> rootClass = this.advised.getTargetClass();
			Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");

			Class<?> proxySuperClass = rootClass;
			if (ClassUtils.isCglibProxyClass(rootClass)) {
				proxySuperClass = rootClass.getSuperclass();
				Class<?>[] additionalInterfaces = rootClass.getInterfaces();
				for (Class<?> additionalInterface : additionalInterfaces) {
					this.advised.addInterface(additionalInterface);
				}
			}

			// Validate the class, writing log messages as necessary.
			validateClassIfNecessary(proxySuperClass, classLoader);
			// 配置 Cglib 增强
			// Configure CGLIB Enhancer...
			Enhancer enhancer = createEnhancer();
			if (classLoader != null) {
				enhancer.setClassLoader(classLoader);
				if (classLoader instanceof SmartClassLoader &&
						((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
					enhancer.setUseCache(false);
				}
			}
			enhancer.setSuperclass(proxySuperClass);
			enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
			enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
			enhancer.setStrategy(new ClassLoaderAwareUndeclaredThrowableStrategy(classLoader));

			Callback[] callbacks = getCallbacks(rootClass);
			Class<?>[] types = new Class<?>[callbacks.length];
			for (int x = 0; x < types.length; x++) {
				types[x] = callbacks[x].getClass();
			}
			// fixedInterceptorMap only populated at this point, after getCallbacks call above
			enhancer.setCallbackFilter(new ProxyCallbackFilter(
					this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
			enhancer.setCallbackTypes(types);

			// ⽣成代理类,并且创建⼀个代理类的实例
			// Generate the proxy class and create a proxy instance.
			return createProxyClassAndInstance(enhancer, callbacks);
		}
		catch (CodeGenerationException | IllegalArgumentException ex) {
			throw new AopConfigException("Could not generate CGLIB subclass of " + this.advised.getTargetClass() +
					": Common causes of this problem include using a final class or a non-visible class",
					ex);
		}
		catch (Throwable ex) {
			// TargetSource.getTarget() failed
			throw new AopConfigException("Unexpected AOP exception", ex);
		}
	}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值