Using an Autoproxy
So far, you've explicitly and manually created each proxy. Spring also has the ability to automatically create a proxy, or autoproxy. The goal of the autoproxy is to apply the same signature to a number of methods. In this lab, you'll use an autoproxy to attach profiling code to all of the classes in the application.
How do I do that?
Spring 1.1 lets you do autoproxying in two ways. You can:
Specify a configuration and apply it to named beans context.
Use source-level metadata (added to the JDK in Java 5, but available through Apache Commons annotations today).
In this example, you're going to be proxying named beans. As before, you'll first need some advice. Example 6-7 shows around advice that prints profiling statements before and after Spring enters a method.
Example 6-7. ProfilingInterceptory.java
public class ProfilingInterceptor implements MethodInterceptor{
public Object invoke(MethodInvocation methodInvocation)
throws Throwable {
long start = System.currentTimeMillis( );
Object results = methodInvocation.proceed( );
long end = System.currentTimeMillis( );
System.out.println("Method: " +
methodInvocation.getMethod( ).getName( ) + " took " +
(end - start) + " ms.");
return results;
}
}Next, configure it. Don't specify a single target, but a regular expression. Spring will apply the advice to all of the beans that match. Specify the autoproxy, the advice, and the targets (Example 6-8).
Example 6-8. RentABike-servlet.xml
<bean name="profilerAround" class="com.springbook.interceptors.ProfilingInterceptor"/> ...