Skip to Main Content
Spring: A Developer's Notebook
book

Spring: A Developer's Notebook

by Bruce Tate, Justin Gehtland
April 2005
Intermediate to advanced content levelIntermediate to advanced
216 pages
4h 44m
English
O'Reilly Media, Inc.
Content preview from Spring: A Developer's Notebook

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"/> ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaBeans Unleashed

JavaBeans Unleashed

Dr. Donald Doherty, Rick Leinecker
Beginning Spring

Beginning Spring

Mert Caliskan, Kenan Sevindik, Rod Johnson, Jürgen Höller
Hibernate Search in Action

Hibernate Search in Action

Emmanuel Bernard, John Griffin

Publisher Resources

ISBN: 0596009100Supplemental ContentErrata Page