我們知道Spring是通過JDK或者CGLib實(shí)現(xiàn)動態(tài)代理的,今天我們討論一下JDK實(shí)現(xiàn)動態(tài)代理的原理。
一、簡述
Spring在解析Bean的定義之后會將Bean的定義生成一個(gè)BeanDefinition對象并且由BeanDefinitionHolder對象持有。在這個(gè)過程中,如果Bean需要被通知切入,BeanDefinition會被重新轉(zhuǎn)換成一個(gè)proxyDefinition(其實(shí)也是一個(gè)BeanDefinition對象,只不過描述的是一個(gè)ProxyFactoryBean)。ProxyFactoryBean是一個(gè)實(shí)現(xiàn)了FactoryBean的接口,用來生成被被切入的對象。Spring AOP的實(shí)現(xiàn)基本上是通過ProxyFactoryBean實(shí)現(xiàn)的。我們今天討論的重點(diǎn)也是這個(gè)類。
在討論P(yáng)roxyFactoryBean之前,我們先看一下一個(gè)BeanDefinition轉(zhuǎn)換成proxyDefintion的過程。
public final BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definitionHolder, ParserContext parserContext) {
BeanDefinitionRegistry registry = parserContext.getRegistry();
// get the root bean name - will be the name of the generated proxy factory bean
String existingBeanName = definitionHolder.getBeanName();
BeanDefinition targetDefinition = definitionHolder.getBeanDefinition();
BeanDefinitionHolder targetHolder = new BeanDefinitionHolder(targetDefinition, existingBeanName + ".TARGET");
// delegate to subclass for interceptor definition
BeanDefinition interceptorDefinition = createInterceptorDefinition(node);
// generate name and register the interceptor
String interceptorName = existingBeanName + "." + getInterceptorNameSuffix(interceptorDefinition);
BeanDefinitionReaderUtils.registerBeanDefinition(
new BeanDefinitionHolder(interceptorDefinition, interceptorName), registry);
BeanDefinitionHolder result = definitionHolder;
if (!isProxyFactoryBeanDefinition(targetDefinition)) {
// create the proxy definition 這里創(chuàng)建proxyDefinition對象,并且從原來的BeanDefinition對象中復(fù)制屬性
RootBeanDefinition proxyDefinition = new RootBeanDefinition();
// create proxy factory bean definition
proxyDefinition.setBeanClass(ProxyFactoryBean.class);
proxyDefinition.setScope(targetDefinition.getScope());
proxyDefinition.setLazyInit(targetDefinition.isLazyInit());
// set the target
proxyDefinition.setDecoratedDefinition(targetHolder);
proxyDefinition.getPropertyValues().add("target", targetHolder);
// create the interceptor names list
proxyDefinition.getPropertyValues().add("interceptorNames", new ManagedList<String>());
// copy autowire settings from original bean definition.
proxyDefinition.setAutowireCandidate(targetDefinition.isAutowireCandidate());
proxyDefinition.setPrimary(targetDefinition.isPrimary());
if (targetDefinition instanceof AbstractBeanDefinition) {
proxyDefinition.copyQualifiersFrom((AbstractBeanDefinition) targetDefinition);
}
// wrap it in a BeanDefinitionHolder with bean name
result = new BeanDefinitionHolder(proxyDefinition, existingBeanName);
}
addInterceptorNameToList(interceptorName, result.getBeanDefinition());
return result;
}
二、ProxyFactoryBean的原理
我們先來看一下ProxyFactoryBean的繼承關(guān)系:

ProxyFactoryBean實(shí)現(xiàn)了FactoryBean、BeanClassLoaderAware、BeanFactoryAware接口,這里就不多說了。ProxyCreatorSupport這個(gè)類則是創(chuàng)建代理對象的關(guān)鍵所在?! ∥覀兿葋砜纯串a(chǎn)生代理對象的方法:
public Object getObject() throws BeansException {
initializeAdvisorChain();
if (isSingleton()) {
//單例
return getSingletonInstance();
}
else {
if (this.targetName == null) {
logger.warn("Using non-singleton proxies with singleton targets is often undesirable. " +
"Enable prototype proxies by setting the 'targetName' property.");
}
//非單例
return newPrototypeInstance();
}
}
initializeAdvisorChain() 方法是將通知鏈實(shí)例化。然后判斷對象是否要生成單例而選擇調(diào)用不同的方法,這里我們只看生成單例對象的方法。
private synchronized Object getSingletonInstance() {
if (this.singletonInstance == null) {
this.targetSource = freshTargetSource();
//如果以接口的方式代理對象
if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {
// Rely on AOP infrastructure to tell us what interfaces to proxy.
Class<?> targetClass = getTargetClass();
if (targetClass == null) {
throw new FactoryBeanNotInitializedException("Cannot determine target class for proxy");
}
//獲取目標(biāo)類實(shí)現(xiàn)的所有接口,并注冊給父類的interfaces屬性,為jdk動態(tài)代理做準(zhǔn)備
setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));
}
// Initialize the shared singleton instance.
super.setFrozen(this.freezeProxy);
//這里產(chǎn)生代理對象
this.singletonInstance = getProxy(createAopProxy());
}
return this.singletonInstance;
}
我們可以看到,產(chǎn)生代理對象是通過getProxy()方法實(shí)現(xiàn)的,這個(gè)方法我們看一下:
protected Object getProxy(AopProxy aopProxy) {
return aopProxy.getProxy(this.proxyClassLoader);
}
AopProxy對象的getProxy()方法產(chǎn)生我們需要的代理對象,究竟AopProxy這個(gè)類是什么,我們接下來先看一下產(chǎn)生這個(gè)對象的方法createAopProxy():
protected final synchronized AopProxy createAopProxy() {
if (!this.active) {
activate();
}
return getAopProxyFactory().createAopProxy(this);
}
createAopProxy方法:
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
//目標(biāo)對象不是接口類的實(shí)現(xiàn)或者沒有提供代理接口
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);
}
}
在這里我們只看JdkDynamicAopProxy這個(gè)類的實(shí)現(xiàn),我們前面提到,真正代理對象的生成是由AopProxy的getProxy方法完成的,這里我們看一下JdkDynamicAopProxy的getProxy方法,這也是本文討論的重點(diǎn):
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);
findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}
我們看可以很清楚的看到,代理對象的生成直接使用了jdk動態(tài)代理:Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);而代理邏輯是通過實(shí)現(xiàn)了InvocationHandler接口的invoke方法實(shí)現(xiàn)的。而這里用到的實(shí)現(xiàn)了InvocationHandler接口的類就是JdkDynamicAopProxy自身。JdkDynamicAopProxy自身實(shí)現(xiàn)了InvocationHandler接口,完成了Spring AOP攔截器鏈攔截等一系列邏輯,我們看一下JdkDynamicAopProxy的invoke方法的具體實(shí)現(xiàn):
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
MethodInvocation invocation;
Object oldProxy = null;
boolean setProxyContext = false;
TargetSource targetSource = this.advised.targetSource;
Class<?> targetClass = null;
Object target = null;
try {
//沒有重寫equals方法
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// The target does not implement the equals(Object) method itself.
return equals(args[0]);
}
//沒有重寫hashCode方法
if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// The target does not implement the hashCode() method itself.
return hashCode();
}
//代理的類是Advised,這里直接執(zhí)行,不做任何代理
if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
method.getDeclaringClass().isAssignableFrom(Advised.class)) {
// Service invocations on ProxyConfig with the proxy config...
return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
}
Object retVal;
if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
// May be null. Get as late as possible to minimize the time we "own" the target,
// in case it comes from a pool.
//獲得代理對象
target = targetSource.getTarget();
if (target != null) {
targetClass = target.getClass();
}
// Get the interception chain for this method.
//獲得已經(jīng)定義的攔截器鏈
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
// Check whether we have any advice. If we don't, we can fallback on direct
// reflective invocation of the target, and avoid creating a MethodInvocation.
if (chain.isEmpty()) {
// We can skip creating a MethodInvocation: just invoke the target directly
// Note that the final invoker must be an InvokerInterceptor so we know it does
// nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
//攔截器鏈?zhǔn)强盏?,直接?zhí)行需要代理的方法
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, args);
}
else {
// We need to create a method invocation...
//這里是調(diào)用攔截器鏈的地方,先創(chuàng)建一個(gè)MethodInvocation對象,然后調(diào)用該對象的proceed方法完成攔截器鏈調(diào)用
invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
// Proceed to the joinpoint through the interceptor chain.
retVal = invocation.proceed();
}
// Massage return value if necessary.
Class<?> returnType = method.getReturnType();
//這里處理返回值,判斷返回值和方法需要的返回是否一致
if (retVal != null && retVal == target && returnType.isInstance(proxy) &&
!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
// Special case: it returned "this" and the return type of the method
// is type-compatible. Note that we can't help if the target sets
// a reference to itself in another returned object.
retVal = proxy;
} else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
throw new AopInvocationException("Null return value from advice does not match primitive return type for: " + method);
}
return retVal;
}
finally {
if (target != null && !targetSource.isStatic()) {
// Must have come from TargetSource.
targetSource.releaseTarget(target);
}
if (setProxyContext) {
// Restore old proxy.
AopContext.setCurrentProxy(oldProxy);
}
}
}
攔截器鏈的調(diào)用
從上面的代碼和注釋中我們可以看到spring實(shí)現(xiàn)aop的主要流程,具體如何調(diào)用攔截器鏈,我們來看一下MethodInvocation的proceed方法
public Object proceed() throws Throwable {
// We start with an index of -1 and increment early.
// currentInterceptorIndex是從-1開始的,所以攔截器鏈調(diào)用結(jié)束的時(shí)候index是 this.interceptorsAndDynamicMethodMatchers.size() - 1
// 調(diào)用鏈結(jié)束后執(zhí)行目標(biāo)方法
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint();
}
// 獲得當(dāng)前處理到的攔截器
Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
// 這里判斷是否是InterceptorAndDynamicMethodMatcher,如果是,這要判斷是否匹配methodMatcher,不匹配則此攔截器不生效
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
// Evaluate dynamic method matcher here: static part will already have
// been evaluated and found to match.
InterceptorAndDynamicMethodMatcher dm =
(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
return dm.interceptor.invoke(this);
}
else {
// Dynamic matching failed.
// Skip this interceptor and invoke the next in the chain.
return proceed();
}
}
else {
// It's an interceptor, so we just invoke it: The pointcut will have
// been evaluated statically before this object was constructed.
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
proceed()方法是一個(gè)遞歸方法,我們可以根據(jù)代碼的注釋知道大體邏輯,InterceptorAndDynamicMethodMatcher的代碼如下,我們可以看到,InterceptorAndDynamicMethodMatcher 持有一個(gè)MethodInterceptor 對象和一個(gè)MethodMatcher 對象,在攔截器鏈調(diào)用過程中,如果攔截器是InterceptorAndDynamicMethodMatcher ,則會先根據(jù)MethodMatcher 判斷是否匹配,匹配MethodInterceptor 才會生效。
class InterceptorAndDynamicMethodMatcher {
final MethodInterceptor interceptor;
final MethodMatcher methodMatcher;
public InterceptorAndDynamicMethodMatcher(MethodInterceptor interceptor, MethodMatcher methodMatcher) {
this.interceptor = interceptor;
this.methodMatcher = methodMatcher;
}
}
至于MethodInterceptor 是什么,MethodInterceptor 的邏輯是怎么樣的,我們可以看一下MethodInterceptor 的一個(gè)子類AfterReturningAdviceInterceptor的實(shí)現(xiàn):
public class AfterReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice, Serializable { private final AfterReturningAdvice advice; /** * Create a new AfterReturningAdviceInterceptor for the given advice. * @param advice the AfterReturningAdvice to wrap */ public AfterReturningAdviceInterceptor(AfterReturningAdvice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; } @Override public Object invoke(MethodInvocation mi) throws Throwable { Object retVal = mi.proceed(); this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis()); return retVal; }}
AfterReturningAdviceInterceptor的作用是在被代理的方法返回結(jié)果之后添加我們需要的處理邏輯,其實(shí)現(xiàn)方式我們可以看到,先調(diào)用MethodInvocation 的proceed,也就是先繼續(xù)處理攔截器鏈,等調(diào)用完成后執(zhí)行我們需要的邏輯:this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
到這里,spring使用jdk動態(tài)代理實(shí)現(xiàn)aop的分析基本上結(jié)束,其中攔截器鏈的調(diào)用比較難懂而且比較重要,需要的同學(xué)可以多看看這一塊。
在程序員這條路上遇到瓶頸的朋友可以加入群:654675708 大家一起來提升進(jìn)步 但要備注好信息 注! 有Java高級大牛直播講解知識點(diǎn),分享知識,有五大專題都是各位老師多年工作經(jīng)驗(yàn)的梳理和總結(jié),帶著大家全面、科學(xué)地建立自己的技術(shù)體系和技術(shù)認(rèn)知
階段一:工程化技術(shù)-提升效率 才能有更多的時(shí)間來思考
階段二:源碼分析-成為一個(gè)內(nèi)功深厚的程序員
階段三:高性能 分布式 高可用-進(jìn)入互聯(lián)網(wǎng)公司不再是你的難題
階段四:性能調(diào)優(yōu)-我不甘心只做一個(gè)程序員 我還有更高的成就
階段五:項(xiàng)目實(shí)戰(zhàn)-理論與時(shí)間實(shí)踐相結(jié)合 你離夢想的距離只學(xué)要你點(diǎn)起腳尖