Results 1 to 3 of 3

Thread: When/how to use a JDK dynamic proxy

  1. #1
    Join Date
    Aug 2007
    Posts
    2

    Default When/how to use a JDK dynamic proxy

    Hi,

    I'm trying to understand Spring-AOP and am still confused by the AOP-proxies. Especially when it comes to classes that implement interfaces.

    From the SpringFramework 2.x manual:
    "If the target class implements one (or more) interfaces, then the type of proxy that is created depends on the configuration of the ProxyFactoryBean.

    If the proxyTargetClass property of the ProxyFactoryBean has been set to true, then a CGLIB-based proxy will be created. "


    When the proxyTargetClass is false, I presume a JDK proxy gets created. When I try to fetch it from the context via

    Person p = (Person) ctx.getBean("diner");

    I get the infamous error

    java.lang.ClassCastException: $Proxy0 cannot be cast to ...

    I've seen that the solution is to set the proxyTargetClass to true, causing the CGLIB proxy to be used, but I do not understand

    1) How would one retrieve the JDK-proxy bean without the ClassCastException?
    2) Under what circumstances would using the JDK-proxy be favored over the CGLIB-proxy?

    Thanks.

  2. #2
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,625

    Default

    1) How would one retrieve the JDK-proxy bean without the ClassCastException?
    Cast it to one of the implemented interfaces, JDK dynamic proxies are only created for the interfaces implemented. So in y our case probably Comparable is the only interface you can use.

    You don't use an Person interface but only a class so a JDK Dynamix proxy is created only for the implemented interfaces. Hence no cast to Person can be done.

    2) Under what circumstances would using the JDK-proxy be favored over the CGLIB-proxy?
    There is no easy answer for that. But as a rule of thumb, when you programm to interfaces you can almost do everything with a JDK dynamic proxy, else you need CGLIB.
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  3. #3
    Join Date
    Nov 2005
    Location
    Reutlingen, Germany
    Posts
    2,098

    Default

    Marten, didn't you just want to point to my Spring AOP summary post

    Joerg
    This post can contain insufficient information.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •