Spring AOP Pointcut Annotation


 

Spring AOP Pointcut Annotation

In this tutorial you will learn, how to use annotation in poitcut.

In this tutorial you will learn, how to use annotation in poitcut.

Spring AOP Pointcut Annotation

In Spring AOP pointcuts determine join points of interest, and thus enable us to control when advice executes.In the @AspectJ annotation-style of AOP, a pointcut signature is
provided by a regular method definition, and the pointcut expression is indicated using the @Pointcut annotation. for example:-
            @Pointcut("execution(* transfer(..))")// the pointcut expression
               private void anyOldTransfer() {}// the pointcut signature

MainClaz.java

package roseindia.net.main;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;

import org.aopalliance.aop.Advice;
import org.springframework.aop.Advisor;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.annotation.AnnotationMatchingPointcut;

public class MainClaz {
	public static void main(String[] args) {
		SimpleBean target = new SimpleBean();
		AnnotationMatchingPointcut pointcut = new AnnotationMatchingPointcut(
				null, SimpleAnnotation.class);
		Advice advice = new SimpleBeforeAdvice();
		Advisor advisor = new DefaultPointcutAdvisor(pointcut, advice);
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.setTarget(target);
		proxyFactory.addAdvisor(advisor);
		SimpleBean proxy = (SimpleBean) proxyFactory.getProxy();
		proxy.getName();
		proxy.getAge();
	}
}

class SimpleBeforeAdvice implements MethodBeforeAdvice {
	public void before(Method method, Object[] objects, Object object)
			throws Throwable {
		System.out.println("Before " + method + " method");
	}
}

class AnnotationAfterAdvice implements AfterReturningAdvice {
	public void afterReturning(Object object, Method method, Object[] objects,
			Object obj) throws Throwable {
		System.out.print("Annotated After: " + method + " method");
	}
}

@Target( { ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@interface SimpleAnnotation {
}

@SimpleAnnotation
class SimpleBean {
	@SimpleAnnotation
	public String getName() {
		return "Vinay";
	}

	public void setName(String name) {
	}

	public int getAge() {
		return 24;
	}
}

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


Before public java.lang.String roseindia.net.main.SimpleBean.getName() method

Download this example code

Ads