Spring5源码(36)-SpringAop创建代理(二)

简介: Spring5源码(36)-SpringAop创建代理(二)


上一篇中的分析已经可以获取到适合给定bean的所有增强,接下来就是创建代理了。

/**
 * 如果需要则包装该bean,例如该bean可以被代理
 * 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) {
    // 1、如果已经处理过或者不需要创建代理,则返回
    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;
    }
    // 2、创建代理
    // 2.1 根据指定的bean获取所有的适合该bean的增强
    Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
    if (specificInterceptors != DO_NOT_PROXY) {
        // 2.2 为指定bean创建代理
        this.advisedBeans.put(cacheKey, Boolean.TRUE);
        Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
        this.proxyTypes.put(cacheKey, proxy.getClass());
        return proxy;
    }
    // 3、缓存
    this.advisedBeans.put(cacheKey, Boolean.FALSE);
    return bean;
}
1.创建代理流程分析

/**
 * 为给定的bean创建代理
 * Create an AOP proxy for the given bean.
 * @param beanClass the class of the bean
 * @param beanName the name of the bean
 * @param specificInterceptors the set of interceptors that is
 * specific to this bean (may be empty, but not null)
 * @param targetSource the TargetSource for the proxy,
 * already pre-configured to access the bean
 * @return the AOP proxy for the bean
 * @see #buildAdvisors
 */
protected Object createProxy(Class<?> beanClass,
                             @Nullable String beanName,
                             @Nullable Object[] specificInterceptors,
                             TargetSource targetSource) {
    // 1、当前beanFactory是ConfigurableListableBeanFactory类型,则尝试暴露当前bean的target class
    if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
        AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
    }
    // 2、创建ProxyFactory并配置
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.copyFrom(this);
    // 是否直接代理目标类以及接口
    if (!proxyFactory.isProxyTargetClass()) {
        // 确定给定bean是否应该用它的目标类而不是接口进行代理
        if (shouldProxyTargetClass(beanClass, beanName)) {
            proxyFactory.setProxyTargetClass(true);
        }
        // 检查给定bean类上的接口,如果合适的话,将它们应用到ProxyFactory。即添加代理接口
        else {
            evaluateProxyInterfaces(beanClass, proxyFactory);
        }
    }
    // 3、确定给定bean的advisors,包括特定的拦截器和公共拦截器,是否适配Advisor接口。
    Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
    // 设置增强
    proxyFactory.addAdvisors(advisors);
    // 设置代理目标
    proxyFactory.setTargetSource(targetSource);
    // 定制proxyFactory(空的模板方法,可在子类中自己定制)
    customizeProxyFactory(proxyFactory);
    // 锁定proxyFactory
    proxyFactory.setFrozen(this.freezeProxy);
    if (advisorsPreFiltered()) {
        proxyFactory.setPreFiltered(true);
    }
    // 4、创建代理
    return proxyFactory.getProxy(getProxyClassLoader());
}

具体的流程处理,代码注释里已经写的很清楚了,接下来看第四步,创建代理的具体过程。

public Object getProxy(@Nullable ClassLoader classLoader) {
    return createAopProxy().getProxy(classLoader);
}
protected final synchronized AopProxy createAopProxy() {
    if (!this.active) {
        activate();
    }
    return getAopProxyFactory().createAopProxy(this);
}

从上面的代码可以看到,创建代理的具体工作委托给了AopProxyFactory的createAopProxy方法。

/**
 * 创建代理
 * 1、config.isOptimize():判断通过CGLIB创建的代理是否使用了优化策略
 * 2、config.isProxyTargetClass():是否配置了proxy-target-class为true
 * 3、hasNoUserSuppliedProxyInterfaces(config):是否存在代理接口
 * 4、targetClass.isInterface()-->目标类是否为接口
 * 5、Proxy.isProxyClass-->如果targetClass类是代理类,则返回true,否则返回false。
 *
 * @param config the AOP configuration in the form of an AdvisedSupport object
 * @return
 * @throws AopConfigException
 */
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
    // 1、判断是否需要创建CGLIB动态代理
    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.");
        }
        // todo 这里有疑问 即
        // targetClass.isInterface()
        // Proxy.isProxyClass(targetClass)
        // 什么情况下会生效
        if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
            // 创建jdk动态代理
            return new JdkDynamicAopProxy(config);
        }
        // 创建CGLIB动态代理
        return new ObjenesisCglibAopProxy(config);
    }
    // 2、默认创建JDK动态代理
    else {
        return new JdkDynamicAopProxy(config);
    }
}

这里我们终于看到了判断CGLIB和JDK动态代理的判断条件,这也是面试会碰到的一个常见的问题。

我们先分析第一个if判断里的条件:

  • config.isOptimize():判断通过CGLIB创建的代理是否使用了优化策略
    该条件取值于ProxyConfig类的optimize属性。此属性标记是否对代理进行优化。启动优化通常意味着在代理对象被创建后,增强的修改将不会生效,因此默认值为false。如果exposeProxy设置为true,即使optimize为true也会被忽略。
  • config.isProxyTargetClass():是否配置了proxy-target-class为true
    该条件取值于ProxyConfig类的proxyTargetClass属性。此属性标记是否直接对目标类进行代理,而不是通过接口产生代理。
  • hasNoUserSuppliedProxyInterfaces(config):是否存在代理接口

满足以上三者条件的任何一个,则会考虑开启CGLIB动态代理,但是在该if条件里还有另外一层判断 targetClass.isInterface() || Proxy.isProxyClass(targetClass),即如果目标类本身就是一个接口,或者目标类是由Proxy.newProxyInstance()Proxy.getProxyClass()生成时,则依然采用jdk动态代理。(关于这两种情况的实例,网上没有找到例子,了解的同学可以留言哈!

到这里,代理的创建过程勉强的分析完了。。。,接下来我们看获取代理的过程。

2.获取CGLIB动态代理

public Object getProxy(@Nullable ClassLoader classLoader) {
    logger.info("Creating CGLIB proxy: target source is " + this.advised.getTargetSource());
    try {
        Class<?> rootClass = this.advised.getTargetClass();
        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);
        // 新建并配置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);
    }
}
3.获取JDK动态代理

public Object getProxy(@Nullable ClassLoader classLoader) {
    logger.info("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
    // 确定用于给定AOP配置的代理的完整接口集。
    Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
    // 判断被代理接口有没有重写equals和hashCode方法
    findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
    // 为接口创建代理
    return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}
4.总结

代理的具体创建过程与我们之前篇幅中分析的过程大致相同,这里不详细的分析了,感兴趣的同学,可以自己跟踪调试一下代码。

另外在本篇中还有一个疑问就是判断创建代理类型里的 targetClass.isInterface() || Proxy.isProxyClass(targetClass),这句话会在什么样的场景下生效,知道的同学请留言,万分感激。。



作者:闲来也无事

链接:https://www.jianshu.com/p/ee41c5fee6ff

来源:简书

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

上一篇中的分析已经可以获取到适合给定bean的所有增强,接下来就是创建代理了。

/**
 * 如果需要则包装该bean,例如该bean可以被代理
 * 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) {
    // 1、如果已经处理过或者不需要创建代理,则返回
    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;
    }
    // 2、创建代理
    // 2.1 根据指定的bean获取所有的适合该bean的增强
    Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
    if (specificInterceptors != DO_NOT_PROXY) {
        // 2.2 为指定bean创建代理
        this.advisedBeans.put(cacheKey, Boolean.TRUE);
        Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
        this.proxyTypes.put(cacheKey, proxy.getClass());
        return proxy;
    }
    // 3、缓存
    this.advisedBeans.put(cacheKey, Boolean.FALSE);
    return bean;
}
1.创建代理流程分析

/**
 * 为给定的bean创建代理
 * Create an AOP proxy for the given bean.
 * @param beanClass the class of the bean
 * @param beanName the name of the bean
 * @param specificInterceptors the set of interceptors that is
 * specific to this bean (may be empty, but not null)
 * @param targetSource the TargetSource for the proxy,
 * already pre-configured to access the bean
 * @return the AOP proxy for the bean
 * @see #buildAdvisors
 */
protected Object createProxy(Class<?> beanClass,
                             @Nullable String beanName,
                             @Nullable Object[] specificInterceptors,
                             TargetSource targetSource) {
    // 1、当前beanFactory是ConfigurableListableBeanFactory类型,则尝试暴露当前bean的target class
    if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
        AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
    }
    // 2、创建ProxyFactory并配置
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.copyFrom(this);
    // 是否直接代理目标类以及接口
    if (!proxyFactory.isProxyTargetClass()) {
        // 确定给定bean是否应该用它的目标类而不是接口进行代理
        if (shouldProxyTargetClass(beanClass, beanName)) {
            proxyFactory.setProxyTargetClass(true);
        }
        // 检查给定bean类上的接口,如果合适的话,将它们应用到ProxyFactory。即添加代理接口
        else {
            evaluateProxyInterfaces(beanClass, proxyFactory);
        }
    }
    // 3、确定给定bean的advisors,包括特定的拦截器和公共拦截器,是否适配Advisor接口。
    Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
    // 设置增强
    proxyFactory.addAdvisors(advisors);
    // 设置代理目标
    proxyFactory.setTargetSource(targetSource);
    // 定制proxyFactory(空的模板方法,可在子类中自己定制)
    customizeProxyFactory(proxyFactory);
    // 锁定proxyFactory
    proxyFactory.setFrozen(this.freezeProxy);
    if (advisorsPreFiltered()) {
        proxyFactory.setPreFiltered(true);
    }
    // 4、创建代理
    return proxyFactory.getProxy(getProxyClassLoader());
}

具体的流程处理,代码注释里已经写的很清楚了,接下来看第四步,创建代理的具体过程。

public Object getProxy(@Nullable ClassLoader classLoader) {
    return createAopProxy().getProxy(classLoader);
}
protected final synchronized AopProxy createAopProxy() {
    if (!this.active) {
        activate();
    }
    return getAopProxyFactory().createAopProxy(this);
}

从上面的代码可以看到,创建代理的具体工作委托给了AopProxyFactory的createAopProxy方法。

/**
 * 创建代理
 * 1、config.isOptimize():判断通过CGLIB创建的代理是否使用了优化策略
 * 2、config.isProxyTargetClass():是否配置了proxy-target-class为true
 * 3、hasNoUserSuppliedProxyInterfaces(config):是否存在代理接口
 * 4、targetClass.isInterface()-->目标类是否为接口
 * 5、Proxy.isProxyClass-->如果targetClass类是代理类,则返回true,否则返回false。
 *
 * @param config the AOP configuration in the form of an AdvisedSupport object
 * @return
 * @throws AopConfigException
 */
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
    // 1、判断是否需要创建CGLIB动态代理
    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.");
        }
        // todo 这里有疑问 即
        // targetClass.isInterface()
        // Proxy.isProxyClass(targetClass)
        // 什么情况下会生效
        if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
            // 创建jdk动态代理
            return new JdkDynamicAopProxy(config);
        }
        // 创建CGLIB动态代理
        return new ObjenesisCglibAopProxy(config);
    }
    // 2、默认创建JDK动态代理
    else {
        return new JdkDynamicAopProxy(config);
    }
}

这里我们终于看到了判断CGLIB和JDK动态代理的判断条件,这也是面试会碰到的一个常见的问题。

我们先分析第一个if判断里的条件:

  • config.isOptimize():判断通过CGLIB创建的代理是否使用了优化策略
    该条件取值于ProxyConfig类的optimize属性。此属性标记是否对代理进行优化。启动优化通常意味着在代理对象被创建后,增强的修改将不会生效,因此默认值为false。如果exposeProxy设置为true,即使optimize为true也会被忽略。
  • config.isProxyTargetClass():是否配置了proxy-target-class为true
    该条件取值于ProxyConfig类的proxyTargetClass属性。此属性标记是否直接对目标类进行代理,而不是通过接口产生代理。
  • hasNoUserSuppliedProxyInterfaces(config):是否存在代理接口

满足以上三者条件的任何一个,则会考虑开启CGLIB动态代理,但是在该if条件里还有另外一层判断 targetClass.isInterface() || Proxy.isProxyClass(targetClass),即如果目标类本身就是一个接口,或者目标类是由Proxy.newProxyInstance()Proxy.getProxyClass()生成时,则依然采用jdk动态代理。(关于这两种情况的实例,网上没有找到例子,了解的同学可以留言哈!

到这里,代理的创建过程勉强的分析完了。。。,接下来我们看获取代理的过程。

2.获取CGLIB动态代理

public Object getProxy(@Nullable ClassLoader classLoader) {
    logger.info("Creating CGLIB proxy: target source is " + this.advised.getTargetSource());
    try {
        Class<?> rootClass = this.advised.getTargetClass();
        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);
        // 新建并配置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);
    }
}
3.获取JDK动态代理

public Object getProxy(@Nullable ClassLoader classLoader) {
    logger.info("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
    // 确定用于给定AOP配置的代理的完整接口集。
    Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
    // 判断被代理接口有没有重写equals和hashCode方法
    findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
    // 为接口创建代理
    return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}
4.总结

代理的具体创建过程与我们之前篇幅中分析的过程大致相同,这里不详细的分析了,感兴趣的同学,可以自己跟踪调试一下代码。

另外在本篇中还有一个疑问就是判断创建代理类型里的 targetClass.isInterface() || Proxy.isProxyClass(targetClass),这句话会在什么样的场景下生效,知道的同学请留言,万分感激。。



作者:闲来也无事

链接:https://www.jianshu.com/p/ee41c5fee6ff

来源:简书

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

上一篇中的分析已经可以获取到适合给定bean的所有增强,接下来就是创建代理了。

/**
 * 如果需要则包装该bean,例如该bean可以被代理
 * 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) {
    // 1、如果已经处理过或者不需要创建代理,则返回
    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;
    }
    // 2、创建代理
    // 2.1 根据指定的bean获取所有的适合该bean的增强
    Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
    if (specificInterceptors != DO_NOT_PROXY) {
        // 2.2 为指定bean创建代理
        this.advisedBeans.put(cacheKey, Boolean.TRUE);
        Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
        this.proxyTypes.put(cacheKey, proxy.getClass());
        return proxy;
    }
    // 3、缓存
    this.advisedBeans.put(cacheKey, Boolean.FALSE);
    return bean;
}
1.创建代理流程分析

/**
 * 为给定的bean创建代理
 * Create an AOP proxy for the given bean.
 * @param beanClass the class of the bean
 * @param beanName the name of the bean
 * @param specificInterceptors the set of interceptors that is
 * specific to this bean (may be empty, but not null)
 * @param targetSource the TargetSource for the proxy,
 * already pre-configured to access the bean
 * @return the AOP proxy for the bean
 * @see #buildAdvisors
 */
protected Object createProxy(Class<?> beanClass,
                             @Nullable String beanName,
                             @Nullable Object[] specificInterceptors,
                             TargetSource targetSource) {
    // 1、当前beanFactory是ConfigurableListableBeanFactory类型,则尝试暴露当前bean的target class
    if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
        AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
    }
    // 2、创建ProxyFactory并配置
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.copyFrom(this);
    // 是否直接代理目标类以及接口
    if (!proxyFactory.isProxyTargetClass()) {
        // 确定给定bean是否应该用它的目标类而不是接口进行代理
        if (shouldProxyTargetClass(beanClass, beanName)) {
            proxyFactory.setProxyTargetClass(true);
        }
        // 检查给定bean类上的接口,如果合适的话,将它们应用到ProxyFactory。即添加代理接口
        else {
            evaluateProxyInterfaces(beanClass, proxyFactory);
        }
    }
    // 3、确定给定bean的advisors,包括特定的拦截器和公共拦截器,是否适配Advisor接口。
    Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
    // 设置增强
    proxyFactory.addAdvisors(advisors);
    // 设置代理目标
    proxyFactory.setTargetSource(targetSource);
    // 定制proxyFactory(空的模板方法,可在子类中自己定制)
    customizeProxyFactory(proxyFactory);
    // 锁定proxyFactory
    proxyFactory.setFrozen(this.freezeProxy);
    if (advisorsPreFiltered()) {
        proxyFactory.setPreFiltered(true);
    }
    // 4、创建代理
    return proxyFactory.getProxy(getProxyClassLoader());
}

具体的流程处理,代码注释里已经写的很清楚了,接下来看第四步,创建代理的具体过程。

public Object getProxy(@Nullable ClassLoader classLoader) {
    return createAopProxy().getProxy(classLoader);
}
protected final synchronized AopProxy createAopProxy() {
    if (!this.active) {
        activate();
    }
    return getAopProxyFactory().createAopProxy(this);
}

从上面的代码可以看到,创建代理的具体工作委托给了AopProxyFactory的createAopProxy方法。

/**
 * 创建代理
 * 1、config.isOptimize():判断通过CGLIB创建的代理是否使用了优化策略
 * 2、config.isProxyTargetClass():是否配置了proxy-target-class为true
 * 3、hasNoUserSuppliedProxyInterfaces(config):是否存在代理接口
 * 4、targetClass.isInterface()-->目标类是否为接口
 * 5、Proxy.isProxyClass-->如果targetClass类是代理类,则返回true,否则返回false。
 *
 * @param config the AOP configuration in the form of an AdvisedSupport object
 * @return
 * @throws AopConfigException
 */
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
    // 1、判断是否需要创建CGLIB动态代理
    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.");
        }
        // todo 这里有疑问 即
        // targetClass.isInterface()
        // Proxy.isProxyClass(targetClass)
        // 什么情况下会生效
        if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
            // 创建jdk动态代理
            return new JdkDynamicAopProxy(config);
        }
        // 创建CGLIB动态代理
        return new ObjenesisCglibAopProxy(config);
    }
    // 2、默认创建JDK动态代理
    else {
        return new JdkDynamicAopProxy(config);
    }
}

这里我们终于看到了判断CGLIB和JDK动态代理的判断条件,这也是面试会碰到的一个常见的问题。

我们先分析第一个if判断里的条件:

  • config.isOptimize():判断通过CGLIB创建的代理是否使用了优化策略
    该条件取值于ProxyConfig类的optimize属性。此属性标记是否对代理进行优化。启动优化通常意味着在代理对象被创建后,增强的修改将不会生效,因此默认值为false。如果exposeProxy设置为true,即使optimize为true也会被忽略。
  • config.isProxyTargetClass():是否配置了proxy-target-class为true
    该条件取值于ProxyConfig类的proxyTargetClass属性。此属性标记是否直接对目标类进行代理,而不是通过接口产生代理。
  • hasNoUserSuppliedProxyInterfaces(config):是否存在代理接口

满足以上三者条件的任何一个,则会考虑开启CGLIB动态代理,但是在该if条件里还有另外一层判断 targetClass.isInterface() || Proxy.isProxyClass(targetClass),即如果目标类本身就是一个接口,或者目标类是由Proxy.newProxyInstance()Proxy.getProxyClass()生成时,则依然采用jdk动态代理。(关于这两种情况的实例,网上没有找到例子,了解的同学可以留言哈!

到这里,代理的创建过程勉强的分析完了。。。,接下来我们看获取代理的过程。

2.获取CGLIB动态代理

public Object getProxy(@Nullable ClassLoader classLoader) {
    logger.info("Creating CGLIB proxy: target source is " + this.advised.getTargetSource());
    try {
        Class<?> rootClass = this.advised.getTargetClass();
        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);
        // 新建并配置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);
    }
}
3.获取JDK动态代理

public Object getProxy(@Nullable ClassLoader classLoader) {
    logger.info("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
    // 确定用于给定AOP配置的代理的完整接口集。
    Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
    // 判断被代理接口有没有重写equals和hashCode方法
    findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
    // 为接口创建代理
    return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}
4.总结

代理的具体创建过程与我们之前篇幅中分析的过程大致相同,这里不详细的分析了,感兴趣的同学,可以自己跟踪调试一下代码。

另外在本篇中还有一个疑问就是判断创建代理类型里的 targetClass.isInterface() || Proxy.isProxyClass(targetClass),这句话会在什么样的场景下生效,知道的同学请留言,万分感激。。


目录
相关文章
|
4月前
|
设计模式 Java 开发者
如何快速上手【Spring AOP】?从动态代理到源码剖析(下篇)
Spring AOP的实现本质上依赖于代理模式这一经典设计模式。代理模式通过引入代理对象作为目标对象的中间层,实现了对目标对象访问的控制与增强,其核心价值在于解耦核心业务逻辑与横切关注点。在框架设计中,这种模式广泛用于实现功能扩展(如远程调用、延迟加载)、行为拦截(如权限校验、异常处理)等场景,为系统提供了更高的灵活性和可维护性。
|
8月前
|
前端开发 Java 物联网
智慧班牌源码,采用Java + Spring Boot后端框架,搭配Vue2前端技术,支持SaaS云部署
智慧班牌系统是一款基于信息化与物联网技术的校园管理工具,集成电子屏显示、人脸识别及数据交互功能,实现班级信息展示、智能考勤与家校互通。系统采用Java + Spring Boot后端框架,搭配Vue2前端技术,支持SaaS云部署与私有化定制。核心功能涵盖信息发布、考勤管理、教务处理及数据分析,助力校园文化建设与教学优化。其综合性和可扩展性有效打破数据孤岛,提升交互体验并降低管理成本,适用于日常教学、考试管理和应急场景,为智慧校园建设提供全面解决方案。
504 70
|
9月前
|
存储 监控 数据可视化
SaaS云计算技术的智慧工地源码,基于Java+Spring Cloud框架开发
智慧工地源码基于微服务+Java+Spring Cloud +UniApp +MySql架构,利用传感器、监控摄像头、AI、大数据等技术,实现施工现场的实时监测、数据分析与智能决策。平台涵盖人员、车辆、视频监控、施工质量、设备、环境和能耗管理七大维度,提供可视化管理、智能化报警、移动智能办公及分布计算存储等功能,全面提升工地的安全性、效率和质量。
228 0
|
11月前
|
监控 JavaScript 数据可视化
建筑施工一体化信息管理平台源码,支持微服务架构,采用Java、Spring Cloud、Vue等技术开发。
智慧工地云平台是专为建筑施工领域打造的一体化信息管理平台,利用大数据、云计算、物联网等技术,实现施工区域各系统数据汇总与可视化管理。平台涵盖人员、设备、物料、环境等关键因素的实时监控与数据分析,提供远程指挥、决策支持等功能,提升工作效率,促进产业信息化发展。系统由PC端、APP移动端及项目、监管、数据屏三大平台组成,支持微服务架构,采用Java、Spring Cloud、Vue等技术开发。
405 7
|
Java 关系型数据库 数据库连接
Spring源码解析--深入Spring事务原理
本文将带领大家领略Spring事务的风采,Spring事务是我们在日常开发中经常会遇到的,也是各种大小面试中的高频题,希望通过本文,能让大家对Spring事务有个深入的了解,无论开发还是面试,都不会让Spring事务成为拦路虎。
319 1
|
Java Spring
Spring底层架构源码解析(三)
Spring底层架构源码解析(三)
516 5
|
XML Java 数据格式
Spring底层架构源码解析(二)
Spring底层架构源码解析(二)
244 4
|
Java Spring 容器
Spring IOC、AOP与事务管理底层原理及源码解析
【10月更文挑战第1天】Spring框架以其强大的控制反转(IOC)和面向切面编程(AOP)功能,成为Java企业级开发中的首选框架。本文将深入探讨Spring IOC和AOP的底层原理,并通过源码解析来揭示其实现机制。同时,我们还将探讨Spring事务管理的核心原理,并给出相应的源码示例。
393 9