public Object getProxy(@Nullable ClassLoader classLoader) {
return createAopProxy().getProxy(classLoader);
}
创建 Aop 代理
protected final synchronized AopProxy createAopProxy() {
// 激活代理标志,添加监听器
if (!this.active) {
activate();
}
// 默认 DefaultAopProxyFactory
return getAopProxyFactory().createAopProxy(this);
}
获得 Aop 代理工厂
public ProxyCreatorSupport() {
this.aopProxyFactory = new DefaultAopProxyFactory();
}
public AopProxyFactory getAopProxyFactory() {
return this.aopProxyFactory;
}
Aop 代理工厂获取 Aop 代理
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
/*
config.isOptimize() : 默认为false
config.isProxyTargetClass() : 配置 <aop:aspectj-autoproxy proxy-target-class="true"/> 则为true
hasNoUserSuppliedProxyInterfaces(config): 代理对象是否有接口或者有一个SpringProxy接口
*/
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.");
}
// 如果代理对象是接口或者使用Proxy.newProxyInstance创建的代理,那么使用JDK代理
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
// 代理对象不是接口,那么就得用cglib代理
return new ObjenesisCglibAopProxy(config);
} else {
// 上面的条件不满足,那么都JDK代理
return new JdkDynamicAopProxy(config);
}
}
上面的调用链有点磨叽:
- 首先是 ProxyFactory#getProxy;
- 那么来到了 ProxyCreatorSupport#createAopProxy,这里 getAopProxyFactory 得到了 DefaultAopProxyFactory;
- 继续来到了 DefaultAopProxyFactory#createAopProxy,这里得到了 JdkDynamicAopProxy 或者 ObjenesisCglibAopProxy ;
- 也就是说 _ProxyFactory#getProxy 方法中的 createAopProxy() 方法得到了_JdkDynamicAopProxy 或者 _ObjenesisCglibAopProxy ,然后再调用 _getProxy 得到具体的代理对象。
到此我们获得了AOP代理 JdkDynamicAopProxy 或者 ObjenesisCglibAopProxy ,接下来调用 getProxy() 获得最后我们需要的代理对象!