Spring Proxying Mechanisms_Spring代理机制
Spring Proxying Mechanisms_Spring代理机制
秋风醉了 发表于4年前
Spring Proxying Mechanisms_Spring代理机制
  • 发表于 4年前
  • 阅读 61
  • 收藏 2
  • 点赞 0
  • 评论 0

移动开发云端新模式探索实践 >>>   

摘要: Spring Proxying Mechanisms_Spring代理机制

Spring Proxying Mechanisms_Spring代理机制


Spring AOP uses either JDK dynamic proxies or CGLIB to create the proxy for a given target object. (JDK dynamic proxies are preferred whenever you have a choice).

If the target object to be proxied implements at least one interface then a JDK dynamic proxy will be used. All of the interfaces implemented by the target type will be proxied. If the target object does not implement any interfaces then a CGLIB proxy will be created.

If you want to force the use of CGLIB proxying (for example, to proxy every method defined for the target object, not just those implemented by its interfaces) you can do so. However, there are some issues to consider:

  1. final methods cannot be advised, as they cannot be overridden.

  2. As of Spring 3.2, it is no longer necessary to add CGLIB to your project classpath, as CGLIB classes are repackaged under org.springframework and included directly in the spring-core JAR. This means that CGLIB-based proxy support just works in the same way that JDK dynamic proxies always have.

  3. The constructor of your proxied object(被代理的对象) will be called twice. This is a natural consequence(结果) of the CGLIB proxy model whereby(通过) a subclass(子类) is generated for each proxied object. For each proxied instance, two objects are created: the actual proxied object and an instance of the subclass that implements the advice. This behavior is not exhibited(陈列展览) when using JDK proxies. Usually, calling the constructor of the proxied type twice, is not an issue, as there are usually only assignments taking place and no real logic is implemented in the constructor.

To force the use of CGLIB proxies set the value of the proxy-target-class attribute of the <aop:config> element to true:

<aop:config proxy-target-class="true">
    <!-- other beans defined here... -->

To force CGLIB proxying when using the @AspectJ autoproxy support, set the 'proxy-target-class' attribute of the <aop:aspectj-autoproxy> element to true:

<aop:aspectj-autoproxy proxy-target-class="true"/>


  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 220
博文 581
码字总数 411013
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
* 支付类型