Spring AOP Profiling Example


 

Spring AOP Profiling Example

In this tutorial you will how to implement Profiling in Spring AOP.

In this tutorial you will how to implement Profiling in Spring AOP.

Spring AOP Profiling Example

In this example you will learn about implementation of Spring AOP profiling and can explain how it can be utilised. In this example The profiling aspect will record the start time and end time of each method invocation thus allowing more valuable statistics to be derived at a later point in time.

SimpleBean.java

package roseindia.net;

public class SimpleBean {
	public void sayHi() {
		System.out.println("Hi");
	}

	public void doOtherWork() {
		System.out.println("Doing Other Work");
	}
}

ProfileInterceptorClass.java

package roseindia.net;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.util.StopWatch;

public class ProfileInterceptorClass implements MethodInterceptor {

	@Override
	public Object invoke(MethodInvocation methodInvocation) throws Throwable {
		// TODO Auto-generated method stub
		StopWatch stopWatch = new StopWatch();
		stopWatch.start(methodInvocation.getMethod().getName());
		Object object = methodInvocation.proceed();
		stopWatch.stop();
		timePeriod(methodInvocation, stopWatch.getTotalTimeMillis());
		return object;
	}

	private void timePeriod(MethodInvocation methodInvocation, long time) {
		String methodName = methodInvocation.getMethod().getName();
		System.out.println(methodName + "took time" + time);
	}

}

MainClaz.java

package roseindia.net;

import org.aopalliance.aop.Advice;
import org.springframework.aop.framework.ProxyFactory;

public class MainClaz {
	public static void main(String[] args) {
		SimpleBean simpleBean = getSimpleBean();
		simpleBean.sayHi();
		simpleBean.doOtherWork();
	}

	private static SimpleBean getSimpleBean() {
		SimpleBean simpleBean = new SimpleBean();
		ProxyFactory proxyFactory = new ProxyFactory();
		Advice advice = new ProfileInterceptorClass();
		proxyFactory.setTarget(simpleBean);
		SimpleBean proxy = (SimpleBean) proxyFactory.getProxy();
		return proxy;
	}
}

When you run this application it will display message as shown below:


Hi
Doing Other Work

Download this example code

Ads