Spring uses the interface to create the proxies. This is the reason you are not able to cast to actual class, but are able to cast to the interface the class is implementing. Spring basically uses the decorator pattern to add additional functionality & then make call to actual class in the proxy.
posted 8 years ago
SPring creates proxy class and that proxy class has the additional methods of advice
So here according to the above example,
the proxy class will have methods of
Am i right ?
One more Question,
In the above example I typecasted Performer with the proxy object of Singer and i invoked perform method throught the reference of Performer.
What if i want to invoke method which is present only in Singer class, let say method xyz() in class Singer ,
than invoking xyz() using performed will give compilation error right ?
It depends on whether Spring is using JDK Proxy of CGLib to create the proxy. If it's using JDK proxy, the generated code looks logically like this
So, SingerProxy implements the Performer interface. It encapsulates the actual object that it's proxying. In the implementation of perform, it gets the actual method that it should call in the encapsulated object, and then invokes the pointcut. The Pointcut will call your around method and then invoke the perform method on the encapsulated object.
CGLib is a bit differrent
SingerProxy extends Singer and inherits all the methods from Singer. In the perform method it invokes the pointcut which does it's thing and then invokes the super.perform
That's why using JDK proxy you cannot cast the proxy to Singer, because the proxy doesn't extend Singer
Again, this is a logical explanation of how it works. In reality, it's quite a bit different. If you are interested in actually going into the details, it would help to debug the code and inspect the proxy object. The debugger will show you all the private and public members of the proxy. If you have the spring sources, you can debug through the spring sources and see how spring creates the proxy.
Get me the mayor's office! I need to tell her about this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop