欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringAOP之代理对象的创建

程序员文章站 2022-06-20 12:25:51
代理对象的创建是在Bean的后置处理器AbstractAutoProxyCreator的后置方法postProcessAfterInitialization中创建的。1.首先进入SpringBean创建主流程的最后一步,后置处理器的执行。AbstractAutowireCapableBeanFactory.classprotected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDe...

代理对象的创建是在Bean的后置处理器AbstractAutoProxyCreator的后置方法postProcessAfterInitialization中创建的。

1.首先进入SpringBean创建主流程的最后一步,后置处理器的执行。

AbstractAutowireCapableBeanFactory.class
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {
			// 执行bean实现的各种Aware接口如:BeanNameAware/BeanFactoryAware
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			// 执行bean的处理器中的before方法
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			// 调用初始化方法如 实现InitializingBean接口的afterPropertiesSet方法,和xml中指的的init-method
			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;
	}

然后进入applyBeanPostProcessorsAfterInitialization方法

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

		Object result = existingBean;
		for (BeanPostProcessor processor : getBeanPostProcessors()) {
			// 当processor为AbstractAutoProxyCreator时进行代理对象创建增强
			Object current = processor.postProcessAfterInitialization(result, beanName);
			if (current == null) {
				return result;
			}
			result = current;
		}
		return result;
	}

进入AbstractAutoProxyCreator的postProcessAfterInitialization中的wrapIfNecessary方法

AbstractAutoProxyCreator.class
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
		//
		if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
			return bean;
		}
		// 当前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;
		}

		// Create proxy if we have advice.
		// 获取当前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;
	}

进入getAdvicesAndAdvisorsForBean方法看下切面如何获取的

AbstractAdvisorAutoProxyCreator.class
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
		// 获取容器里全部切面
		List<Advisor> candidateAdvisors = findCandidateAdvisors();
		// 过滤切入当前bean的切面
		List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
		extendAdvisors(eligibleAdvisors);
		if (!eligibleAdvisors.isEmpty()) {
			// 切面按指定顺序排序
			eligibleAdvisors = sortAdvisors(eligibleAdvisors);
		}
		return eligibleAdvisors;
	}

进入createProxy查看代理对象创建代码

AbstractAutoProxyCreator.class
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 = new ProxyFactory();
		proxyFactory.copyFrom(this);
		// 判断是否强制使用CGLB动态
		if (!proxyFactory.isProxyTargetClass()) {
			if (shouldProxyTargetClass(beanClass, beanName)) {
				proxyFactory.setProxyTargetClass(true);
			}
			else {
				evaluateProxyInterfaces(beanClass, proxyFactory);
			}
		}
		// 把通知和通用的拦截器合并,都是适配成Advisor(特殊的切面,只包含一个通知和切点)
		Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
		// 传入Advisor链,在JDK的JdkDynamicAopProxy(InvocationHandler实现类)的invoke方法中会使用获取全部切面,然后按照链接点遍历执行各个切面的横切逻辑方法
		// 在CGLB的MethodInterceptor接口实现类的intercept方法中会使用。
		proxyFactory.addAdvisors(advisors);
		// 为代理工厂设置参数
		proxyFactory.setTargetSource(targetSource);
		customizeProxyFactory(proxyFactory);

		proxyFactory.setFrozen(this.freezeProxy);
		if (advisorsPreFiltered()) {
			proxyFactory.setPreFiltered(true);
		}
		// 准备工作完成,开始创建代理
		return proxyFactory.getProxy(getProxyClassLoader());
	}

查看真正创建代理类的代码,JDK动态代理创建(CGLB类似)

JdkDynamicAopProxy.class
public Object getProxy(@Nullable ClassLoader classLoader) {
		if (logger.isTraceEnabled()) {
			logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
		}
		Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
		findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
		return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
	}

本文地址:https://blog.csdn.net/yangxiaofei_java/article/details/112087469

相关标签: Spring #aop aop