Spring AOP Hello World Example


 

Spring AOP Hello World Example

In this tutorial you will learn how to configure and run spring aop advice.

In this tutorial you will learn how to configure and run spring aop advice.

Spring AOP Hello World Example

In this tutorial you will learn how to configure Spring AOP advice using BeanFactory.

HelloInterface.java

package roseindia.net;

public interface HelloInterface {
	public void sayHello();

	public void greet();
}

HelloWorldImpl.java

package roseindia.net;

public class HelloWorldImpl implements HelloInterface {

	@Override
	public void greet() {
		// TODO Auto-generated method stub
		System.out.println("Have a nice Day");
	}

	@Override
	public void sayHello() {
		// TODO Auto-generated method stub
		System.out.println("Hello World");
	}

}

SimpleAdvice.java

package roseindia.net;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class SimpleAdvice implements MethodInterceptor {

	@Override
	public Object invoke(MethodInvocation methodInvocation) throws Throwable {
		// TODO Auto-generated method stub
		System.out.println("Hello");
		Object object = methodInvocation.proceed();
		System.out.println("Done.......");
		return object;
	}

}

MainClaz.java

package roseindia.net;

import org.springframework.aop.framework.ProxyFactory;

public class MainClaz {
	public static void main(String[] args) {
		HelloWorldImpl helloWorldImpl = new HelloWorldImpl();
		SimpleAdvice advice = new SimpleAdvice();
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.addAdvice(advice);
		proxyFactory.setTarget(helloWorldImpl);
		HelloWorldImpl proxy = (HelloWorldImpl) proxyFactory.getProxy();
		proxy.sayHello();
		proxy.greet();
	}
}

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


Hello
Hello World
Done.......
Hello
Have a nice Day
Done.......

Download this example code

Ads