I had some problems with this and found the documentation a little light on the ground, so I felt a little primer was in order.
So what is a proxy class?
Well, in Java terms a proxy class is a runtime-created class which acts like a class of a specified set of interfaces. “CGLIB”:http://cglib.sourceforge.net/ is capable of creating proxy classes without having interfaces – it can mimic a specific class.
Why would you want one?
In “Spring”:http://www.springframework.org (and other languages) proxy classes are used to allow the use of AOP interceptors. The proxy implementation calls the Interceptors before/after invoking the underlying object.
What is an Interceptor?
An Interceptor is a class which gets executed before, after, or around a method. By around we mean both before and after. Oh, and it can also be called when a method throws an exception.
Erm, isn’t that what an ‘Advisor’ is for?
Not exactly – in AOP, an Advisor object states “If this happends, do this”. The “do this” is the Interceptor.
So why would I want to use one?
Well, for logging (wrap and log method invocation). For handling transactions. For handling security. For doing fancy things like invoking validation frameworks or updating progress bars.
So how do I use them?
Lets take a simple example straight from the Spring Reference manual. First create a normal bean:
Now create an Interceptor:
Now create a proxy:
If we then request
"personTarget" from the
ApplicationContext, we get a normal
PersonImpl bean. If we request @”person”@ from the
ApplicationContext we get a proxy class that mimics the
Person interface. All method calls to this proxy gets intercepted by
What if I don’t want to intercept all methods?
One way is to use a fancy (deep breath) @RegexpMethodPointcutAroundAdvisor@. Here we create an Advisor object that invokes an @Interceptor@ when a method name matches the given regexp.
You use an @ApplicationContext@ rather than a
Yeah, otherwise proxys don’t work. I’m not sure why. I should probably find out.
So what is automatic proxy creation?
In our simple example, we defined our bean, then defined a proxy. The downside of this is that we could accidently get the actual bean rather than the proxy, which might not be good. Also, we’ll need one proxy per bean – what if we have loads of beans we want to proxy? Automatic proxy creation is a method in Spring of creating a load of Proxy’s simply.
So how do you do it?
Well, lets look at another example (this one lifted from my command framework). first lets create some commands:
Now lets define an Interceptor:
Now lets create proxies for them:
Now all beans ending in @Command@ will be proxied using @debugInterceptor@. If you call @getBean(“someCommand”)@ you’ll get a proxy for the bean rather than the bean itself. We could of listed the bean names, instead we used a regexp. Likewise we could of used multiple Interceptors (or even Advice objects like @RegexpMethodPointcutAroundAdvisor@ implementations).