Mega Code Archive

 
Categories / Java Tutorial / Spring
 

Create A Benchmark with MethodInterceptor

File: Main.java import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.framework.ProxyFactory; import org.springframework.util.StopWatch; public class Main {   public static void main(String[] args) {     Main target = new Main();     ProxyFactory factory = new ProxyFactory();     factory.setTarget(target);     factory.addAdvice(new ProfilingInterceptor());     Main bean = (Main) factory.getProxy();     bean.doSomeWork(10);   }   public void doSomeWork(int noOfTimes) {     for (int x = 0; x < noOfTimes; x++) {     }   } } class ProfilingInterceptor implements MethodInterceptor {   public Object invoke(MethodInvocation invocation) throws Throwable {     StopWatch sw = new StopWatch();     sw.start(invocation.getMethod().getName());     Object returnValue = invocation.proceed();     sw.stop();     System.out.println("Executed method: " + invocation.getMethod().getName());     System.out.println("On object of type: " + invocation.getThis().getClass().getName());     System.out.println("With arguments:");     for (int x = 0; x < invocation.getArguments().length; x++) {       System.out.print(invocation.getArguments()[x]);     }     return returnValue;   }         }