天天看點

Spring-AOP源碼深度剖析:如何建立代理對象,Java百度雲

AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object,org.springframework.beans.factory.support.RootBeanDefinition)

/**
 	*
 	* 初始化Bean
 		包括Bean後置處理器初始化
		Bean的一些初始化方法的執行init-method
		Bean的實作的聲明周期相關接口的屬性注入
 */
protected Object initializeBean(final String beanName, final 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; 
}
           

AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization

@Override
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;
}
           
Spring-AOP源碼深度剖析:如何建立代理對象,Java百度雲

建立代理對象的後置處理器

AbstractAutoProxyCreator#postProcessAfterInitialization

/**
 * Create a proxy with the configured interceptors if the bean is
 * identified as one to proxy by the subclass.
 * @see #getAdvicesAndAdvisorsForBean
 */

@Override
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;
}
           

AbstractAutoProxyCreator#wrapIfNecessary

/**
 * Wrap the given bean if necessary, i.e. if it is eligible for being
proxied.
 * @param bean the raw bean instance
 * @param beanName the name of the bean
 * @param cacheKey the cache key for metadata access
 * @return a proxy wrapping the bean, or the raw bean instance as-is
 */
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;
	}
	// Create proxy if we have advice.
	// 得到所有候選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;
}
           

AbstractAutoProxyCreator#createProxy

/**
 * Create an AOP proxy for the given bean.
 * 為指定 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());
}
           

接着跟進到

ProxyFactory

public class ProxyFactory extends ProxyCreatorSupport {
	public Object getProxy(ClassLoader classLoader) {
 	// 用ProxyFactory建立AopProxy, 然後用AopProxy建立Proxy, 是以這裡重要的是看擷取的AopProxy
 	// 對象是什麼,
 	// 然後進去看怎麼建立動态代理, 提供了兩種:jdk proxy, cglib
 	return createAopProxy().getProxy(classLoader);
 	} 
}

public class ProxyCreatorSupport extends AdvisedSupport {
 	private AopProxyFactory aopProxyFactory;
 
 	public ProxyCreatorSupport() {
 	this.aopProxyFactory = new DefaultAopProxyFactory();
}
 
	protected final synchronized AopProxy createAopProxy() {
 		if (!this.active) {
 			activate();
 		}
 		//先擷取建立AopProxy的工廠, 再由此建立AopProxy
 		return getAopProxyFactory().createAopProxy(this);
 	}
 
 	public AopProxyFactory getAopProxyFactory() {
 	return this.aopProxyFactory;
 	} 
}
           

流程就是用

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()) {
 				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<?>[] interfaces = config.getProxiedInterfaces();
 	return (interfaces.length == 0 || (interfaces.length == 1 && SpringProxy.class.equals(interfaces[0])));
 	} 
}
           

這裡決定建立代理對象是用

JDK Proxy

,還是用

Cglib

了,最簡單的從使用方面使用來說:設定

proxyTargetClass=true

強制使用Cglib 代理,什麼參數都不設并且對象類實作了接口則預設用JDK 代理,如果沒有實作接口則也必須用Cglib

ProxyFactory#getProxy(java.lang.ClassLoader)

------ CglibAopProxy#getProxy(java.lang.ClassLoader)

@Override
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 增強
 		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);


	enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
 	enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
 	enhancer.setStrategy(new ClassLoaderAwareUndeclaredThrowableStrategy(classLoader));
 	Callback[] callbacks = getCallbacks(rootClass);