AspectJ Pointcut Example


 

AspectJ Pointcut Example

In this tutorial you will learn how to use AspectJ pointcut.

In this tutorial you will learn how to use AspectJ pointcut.

AspectJ Pointcut Example

Spring Pointcut implementation using AspectJ weaver to evaluate a pointcut expression. Following is an example of DefaultPointcut using AspectJ.

StudentBean.java

package roseindia.net.bean;

public class StudentBean {
	String name = "James Bond";
	public static int roll = 007;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getRoll() {
		return roll;
	}

	public void setRoll(int roll) {
		this.roll = roll;
	}

}

SimpleAdvice.java

package roseindia.net.advice;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;

public class SimpleAdvice implements AfterReturningAdvice {

	@Override
	public void afterReturning(Object object, Method method, Object[] objects,
			Object object1) throws Throwable {
		// TODO Auto-generated method stub
		System.out.println("After " + method);
	}

}

MainClaz.java

package roseindia.net.main;

import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;

import roseindia.net.advice.SimpleAdvice;
import roseindia.net.bean.StudentBean;

public class MainClaz {
	public static void main(String args[]) {
		StudentBean studentBean = new StudentBean();
		AspectJExpressionPointcut aspectJExpressionPointcut = new AspectJExpressionPointcut();
		aspectJExpressionPointcut
				.setExpression("execution(* roseindia.net.bean..*.get*(..))");
		SimpleAdvice advice = new SimpleAdvice();
		Advisor advisor = new DefaultPointcutAdvisor(aspectJExpressionPointcut,
				advice);
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.setTarget(studentBean);
		proxyFactory.addAdvisor(advisor);
		StudentBean proxy = (StudentBean) proxyFactory.getProxy();
		System.out.println(proxy.getName());
		proxy.setName("Ram");
		System.out.println(proxy.getRoll());
		System.out.println(proxy.getName());
	}
}


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


After public java.lang.String roseindia.net.bean.StudentBean.getName()
James Bond
After public int roseindia.net.bean.StudentBean.getRoll()
7
After public java.lang.String roseindia.net.bean.StudentBean.getName()
Ram

Download this example code

Ads