Home Tutorial Spring Spring3 Aop Spring AOP Profiling Example

 
 

Spring AOP Profiling Example
Posted on: September 13, 2010 at 12:00 AM
Advertisement
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

Advertisement

Related Tags for Spring AOP Profiling Example:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 13, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com