Create A Benchmark with MethodInterceptor : MethodInterceptor « Spring « Java Tutorial






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;
  }

  
    
}
  Download:  Spring-CreateABenchmarkwithMethodInterceptor.zip( 4,745 k)








28.55.MethodInterceptor
28.55.1.Create A Benchmark with MethodInterceptor
28.55.2.Check Invoked Method In MethodInterceptor
28.55.3.Implements MethodInterceptor To Create Profiling Advice
28.55.4.Implements MethodInterceptor