/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/
///////////////////////////////////////////////////////////////////////////////////////
public class WorkerBean {
public void doSomeWork(int noOfTimes) {
for(int x = 0; x < noOfTimes; x++) {
work();
}
}
private void work() {
System.out.print("");
}
}
///////////////////////////////////////////////////////////////////////////////////////
import java.lang.reflect.Method;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.util.StopWatch;
public class ProfilingInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) throws Throwable {
// start the stop watch
StopWatch sw = new StopWatch();
sw.start(invocation.getMethod().getName());
Object returnValue = invocation.proceed();
sw.stop();
dumpInfo(invocation, sw.getTotalTimeMillis());
return returnValue;
}
private void dumpInfo(MethodInvocation invocation, long ms) {
Method m = invocation.getMethod();
Object target = invocation.getThis();
Object[] args = invocation.getArguments();
System.out.println("Executed method: " + m.getName());
System.out.println("On object of type: " + target.getClass().getName());
System.out.println("With arguments:");
for (int x = 0; x < args.length; x++) {
System.out.print(" > " + args[x]);
}
System.out.print("\n");
System.out.println("Took: " + ms + " ms");
}
}
///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.aop.framework.ProxyFactory;
public class ProfilingExample {
public static void main(String[] args) {
WorkerBean bean = getWorkerBean();
bean.doSomeWork(10000000);
}
private static WorkerBean getWorkerBean() {
WorkerBean target = new WorkerBean();
ProxyFactory factory = new ProxyFactory();
factory.setTarget(target);
factory.addAdvice(new ProfilingInterceptor());
return (WorkerBean)factory.getProxy();
}
}
///////////////////////////////////////////////////////////////////////////////////////
ProfilingExample.zip( 1,479 k)