---
title: "Spring ProxyFactoryBean是如何代理Class分析"
author: "hotforcc"
date: "2007-08-25T09:19:33Z"
tags: []
categories: ["非技术"]
slug: "spring-proxyfactorybean-class"
draft: false
lastmod: "2007-08-25T09:19:33Z"
id: 116595
url: "https://hotforcc.iteye.com/blog/116595"
---

1、ProxyFactoryBean 把proxy的创建交给AopProxy去做。

ProxyFactoryBean.javajava 代码

java 代码

01. public class ProxyFactoryBean extends AdvisedSupport
02. implements FactoryBean, BeanFactoryAware, AdvisedSupportListener {
03. public Object getObject() throws BeansException {
04. //invoke AopProxy 去 创建proxy
05. return this.singleton ? getSingletonInstance() : newPrototypeInstance();
06. }
07. //inherited from ProxyConfig
08. public void setAopProxyFactory(AopProxyFactory apf) {
09. this.aopProxyFactory = apf;
10. }
11. //inherited from ProxyConfig
12. public AopProxyFactory getAopProxyFactory() {
13. return this.aopProxyFactory;
14. }
15. }

2.、那么AopProxy又如何获取？答案是从AopProxyFactory获得。这个AopProxyFactory已在ProxyFactoryBean掌控范围内，如上述代码所示。AopProxyFactory interface如下所示：

AopProxyFactory.java

java 代码

 

1. public interface AopProxyFactory {
2. AopProxy createAopProxy(AdvisedSupport advisedSupport) throws AopConfigException;
3. }

3、AopProxy是如何introduce Advised interface的？那要先从AopProxyFactory的implementation说起。

AopProxyFactory的实现类目前只有DefaultAopProxyFactory。这个类的核心方法如下：

           

java 代码

 

01. public AopProxy createAopProxy(AdvisedSupport advisedSupport) throws AopConfigException {
02. if (advisedSupport.isOptimize() || advisedSupport.isProxyTargetClass() ||
03. advisedSupport.getProxiedInterfaces().length == 0) {
04. if (!cglibAvailable) {
05. throw new AopConfigException(
06. "Cannot proxy target class because CGLIB2 is not available. " +
07. "Add CGLIB to the class path or specify proxy interfaces.");
08. }
09. return CglibProxyFactory.createCglibProxy(advisedSupport);
10. } else {
11. eturn new JdkDynamicAopProxy(advisedSupport);
12. }
13. }

这个方法主要是依赖CglibProxyFactory 类和JdkDynamicAopProxy类。这两个类是如何代理所有的接口的呢？

这两个类都是重要接口AopProxy的实现类，这个接口的核心方法是

java 代码

01. public Object getProxy(ClassLoader classLoader)。
02. 其中JdkDynamicAopProxy实现该方法用到的获取需要代理的接口的代码如下：
03. public Object getProxy(ClassLoader classLoader) {
04. if (logger.isDebugEnabled()) {
05. Class targetClass = this.advised.getTargetSource().getTargetClass();
06. logger.debug("Creating JDK dynamic proxy" +
07. (targetClass != null ? " for \[" + targetClass.getName() + "]" : ""));
08. }
09. Class\[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised);
10. return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
11. }

而

           

java 代码

 

1. public Object getProxy(ClassLoader classLoader) {
2. Enhancer enhancer = new Enhancer();
3. enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
4. }

 

从上面可以看出，这两个AopProxy实现方案在获取接口时都是通过AopProxyUtils.completeProxiedInterfaces(this.advised)获取的。该方法如下：

            Advised  interface的实现。前提是是否允许代理该interafce，这由isOpaque方法确定，该方法Return whether proxies created by this configuration should be prevented from being cast to Advised.

java 代码

 

01. /\**
02. * Get complete set of interfaces to proxy. This will always add the Advised interface
03. * unless the AdvisedSupport's "opaque" flag is true.
04. * @return the complete set of interfaces to proxy
05. \*/
06. public static Class\[] completeProxiedInterfaces(AdvisedSupport advised) {
07. // Won't include Advised, which may be necessary.
08. Class\[] specifiedInterfaces = advised.getProxiedInterfaces();
09. Class\[] proxiedInterfaces = specifiedInterfaces;
10. if (!advised.isOpaque() && !advised.isInterfaceProxied(Advised.class)) {
11. // We need to add the Advised interface.
12. proxiedInterfaces = new Class\[specifiedInterfaces.length + 1];
13. proxiedInterfaces\[0] = Advised.class;
14. System.arraycopy(specifiedInterfaces, 0, proxiedInterfaces, 1,specifiedInterfaces.length);
15. }
16. return proxiedInterfaces;
17. }

从这可以看出，是在这强制加了对

4\. 顺便提一下，Advised interface的具体实现又是怎样的，在哪呢？

4.1 在JdkDynamicAopProxy里，

 

 

1. public Object invoke(Object proxy, Method method, Object\[] args) throws Throwable {
2. if (Advised.class == method.getDeclaringClass()) {
3. // service invocations on ProxyConfig with the proxy config
4. return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
5. }
6. }

注意第一个参数是

而AdisedSupport extends ProxyConfig implements Advised，也就是说Advised的默认实现就是AdisedSupport。

 

4.2 在Cglib2AopProxy里

 

           

01. public Object getProxy(ClassLoader classLoader) {
02. Enhancer enhancer = new Enhancer();
03. enhancer.setCallbackFilter(new ProxyCallbackFilter(this.advised));
04. Callback\[] callbacks = getCallbacks(rootClass);
05. }
06. private Callback\[] getCallbacks(Class rootClass) throws Exception {
07. Callback\[] mainCallbacks = new Callback\[]{
08. aopInterceptor, // for normal advice
09. targetInterceptor, // invoke target without considering advice, if optimized
10. new SerializableNoOp(), // no override for methods mapped to this
11. targetDispatcher, this.advisedDispatcher,
12. new EqualsInterceptor(this.advised)
13. };
14. }
15. private class ProxyCallbackFilter implements CallbackFilter {
16. public int accept(Method method) {
17. if (method.getDeclaringClass() == Advised.class) {
18. if (logger.isDebugEnabled()) {
19. logger.debug("Method " + method + " is declared on Advised -    using      DISPATCH\_ADVISED");
20. }
21. return DISPATCH\_ADVISED;// DISPATCH\_ADVISED 值为4.
22. }
23. }
24. }
25. private final transient AdvisedDispatcher advisedDispatcher = new AdvisedDispatcher();
26. /\**
27. * Dispatcher for any methods declared on the Advised class.
28. \*/
29. private class AdvisedDispatcher implements Dispatcher, Serializable {
30. public Object loadObject() throws Exception {
31. return advised;
32. }
33. }

注意

   
Dispatcher extends Callback interface 。

java 代码

this.advised，其实就是ProxyFactoryBean本身，注意在我发表的其天的Spring文章里也曾提到，ProxyFactoryBean extends AdvisedSupport，

java 代码

CglibProxyFactory的getProxy(ClassLoader classLoader)方法如下：